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());




0 0
原创粉丝点击