spring @Value 注入配置文件内容

来源:互联网 发布:武汉关键词优化 编辑:程序博客网 时间:2024/05/21 07:02

</pre>1,在spring配置文件里引入util的命名空间<p></p><p></p><pre name="code" class="html"><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"    <span style="white-space:pre"></span>xmlns:util="http://www.springframework.org/schema/util"</span> xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"default-lazy-init="true">


2,扫描注解组件 @Component,@Service,让bean处在spring的管理下,因为只有在spring管理下的bean,才能使用@Value的方式从配置文件里取值

<!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  --><context:component-scan base-package="com.money"><!-- base-package 如果多个,用“,”分隔 --><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>
</pre><pre name="code" class="html">3,加载配置文件
</pre><pre name="code" class="html"><!-- 加载应用属性实例,可通过  @Value("#{APP_PROP['jdbc.driver']}") String jdbcDriver 方式引用 --><util:properties id="APP_PROP" location="classpath:resources/money.properties" local-override="true"/>
如果要加载多个配置文件,再定义一个就行
<util:properties id="APP_PROP2" location="classpath:resources/money.properties" local-override="true"/>
4,bean里使用,普通java类使用 @Component注解,service 使用,@Service注解,controller使用 @Controller注解
@Componentpublic class Test {//如果是只加载了一个配置文件,可以直接这样写,通过 $ 获取@Value("${resourceUrl.path}")private String tt;//也可以根据xml里配置的id,指定配置文件,通过 # 获取@Value("#{APP_PROP['resourceUrl.path']}")private String tt1;@Value("#{APP_PROP2['resourceUrl.path']}")private String tt2;public String getTt(){return tt;}public String getTt1(){return tt1;}public String getTt2(){return tt2;}}


5,需要注意的是,使用@Value注入后,可以在该类里直接使用,如果要被其他类调用,则在其他类里也需通过注入的方式引用该类</span>
@AutowiredTest test;
只能通过注入的对象调用,如果是通过 new的方式创建的test对象,调用 test.getTt()时返回null


</pre><br /><br /><pre>




0 0
原创粉丝点击