使用@PropertySource加载外部配置文件属性赋值

 时间:2024-10-15 13:18:48

1、新建一个spring组件配置类:package com.gwolf.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.gwolf.vo.Connection;@Configurationpublic class MainConfigOfPropertyValues { @Bean public Connection connection() { return new Connection(); }}

使用@PropertySource加载外部配置文件属性赋值

2、新建一个properties配置文件:jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crudjdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=root

使用@PropertySource加载外部配置文件属性赋值

3、在组件配置类中使用@PropertySource注解导入*.properties配置文件:package com.gwolf.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import com.gwolf.vo.Connection;@Configuration@PropertySource("classpath:dbconfig.properties")public class MainConfigOfPropertyValues { @Bean public Connection connection() { return new Connection(); }}

使用@PropertySource加载外部配置文件属性赋值

4、在VO对象中通过${}注入properties文件中的值到VO中。package 罕铞泱殳com.gwolf.v泠贾高框o;import org.springframework.beans.factory.annotation.Value;public class Connection { @Value("${jdbc.jdbcUrl}") private String jdbcUrl; @Value("${jdbc.driverClass}") private String driverClass; @Value("${jdbc.user}") private String user; @Value("${jdbc.password}") private String password; public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Connection [jdbcUrl=" + jdbcUrl + ", driverClass=" + driverClass + ", user=" + user + ", password=" + password + "]"; } }

使用@PropertySource加载外部配置文件属性赋值

5、编写一个junit测试类,得到容器中的bean对象的值,打印bean的值。pa罕铞泱殳ckage com.gwo造婷用痃lf.test;import org.junit.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import com.gwolf.config.MainConfigOfPropertyValues;public class ComponentTest { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); @Test public void testImport() { String[] beanNames = applicationContext.getBeanDefinitionNames(); System.out.println(applicationContext.getBean("connection")); applicationContext.close(); }}

使用@PropertySource加载外部配置文件属性赋值
  • Oracle 怎么删除和新建用户?
  • securecrt如何导入会话
  • Mybatis中foreach遍历集合
  • java实现SFTP上传、下载文件功能
  • weblogic无法启动管理服务器解决方法
  • 热门搜索
    手抄报花边素材 学生手抄报设计指南 建国手抄报内容 五一的手抄报 电子手抄报怎么做 未来世界手抄报 感恩节英语手抄报 防震手抄报图片大全集 70周年手抄报 获奖手抄报