spring @Value加载配置值
来源:互联网 发布:sm抢购软件 编辑:程序博客网 时间:2024/05/17 19:21
当我们在JAVA代码中使用
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
进行spring 配置文件加载的时候,想把spring.xml文件里边的
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:dataInfo.properties</value>
</list>
</property>
</bean>
dataInfo.properties里边的配置信息通过@Value的注解形式加入到对应的bean属性中,我们看看dataIfno.properties的信息
db.driver=com.mysql.jdbc.Driver
db.username=test
我们首先创建一个bean,如下:
@Component
public class ConfigInfo {
@Value("${db.driver}")
private String dbDriver;
@Value("${db.username}")
private String username;
public String getDbDriver() {
return dbDriver;
}
public void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
public void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}
}
注意如下2点:
1,这个bean必须用@Component注解注明是个组件类
2,属性上用@Value来注入属性值,注解这里使用的是${}符号
同时我们在spring.xml文件要对这个bean类进行加载注入,我们可以通过如下方式进行
<context:component-scan base-package="com.XX" />
这个时候我们的整个spring.xml文件就如下:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:dataInfo.properties</value>
</list>
</property>
</bean>
<!--扫描指定包下的注解,加载组件 -->
<context:component-scan base-package="com.vanke" />
通过这样配置,我们在java代码里边就可以像下边这样调用:
//通过 ClassPathXmlApplicationContext加载spring.xml文件和初始化spring上下文
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
//我们通过@Component和<context:component-scan>标签将对应的组件以及加载进入spring上下文
//所以我们通过如下方式就可以获取到对应的组件,并已经完成了对应值的注入
ConfigInfo objConfigInfo =(ConfigInfo)ac.getBean(ConfigInfo.class);
System.out.println(objConfigInfo.getDbDriver());
- spring @Value加载配置值
- web.xml 配制加载spring上下文及 Spring context-param param-value classpath 配置加载问题
- Spring Boot 01 加载配置文件和获取key/value值
- Spring注解@Value及属性加载配置文件
- 一般加载Spring配置
- spring web 加载配置
- spring初始化配置加载
- spring加载配置web
- spring 加载自定义配置
- Spring通过注解@Value获取properties配置
- spring boot 通过@Value,@ConfigurationProperties获取配置
- spring boot @Value注解读取配置
- spring boot @Value取值
- Spring中@ImportResource和@Value加载资源文件
- JUnit 中加载spring 配置
- Spring Boot 资源加载配置
- spring java bean加载配置
- Spring+SpringMVC配置加载顺序
- c++如何用好struct的构造函数
- PowerDesigner连接oracle数据库时出现由于系统错误 1114 (oracle in oradb11g_home1)指定驱动程序无法加载 sqlstate=IM003
- mysql语句总结
- 几种常用DB驱动和DB连接串,方便大家用各种程序,连接数据库。
- 解决ibatis Dao层实现类无法正常使用注解方式
- spring @Value加载配置值
- NYOJ-括号配对问题
- 字符串解析
- 多线程使用时间函数
- Java学习——正则表达式入门
- 最短路归纳
- Linux:获取当前进程的执行文件的绝对路径
- 【前端】JS引入文件弹窗乱码
- gem install 出现Errno::ECONNRESET: Connection reset by peer - SSL_connect (https://api.rubygems.org