http://www.blogjava.net/wmcoo/articles/333345.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="UTF-8"?> <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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:annotation-config/> <!-- picks up and registers AppConfig as a bean definition --> <context:component-scan base-package="com.web.spring.other" /> <bean class="com.web.spring.other.AppConfig"/> 访法一 <context:property-placeholder location="classpath:jdbc.properties" /> </beans> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.web.spring.other; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration public class AppConfig { private @Value("${jdbc.driverClassName}") String driverClassName; @Bean(initMethod = "init") public JDBCBean jdbc(){ JDBCBean jdbc=new JDBCBean(); jdbc.setDriverClassName(driverClassName); return jdbc; } } |
在applaction.xml也可以直接使用:
jdbc.driverClassName=org.hsqldb.jdbcDriver
另一种方法:spring 3中新增的@value注解
http://jackyrong.iteye.com/blog/1330946
在spring 3.0中,可以通过使用@value,对一些如xxx.properties文件
中的文件,进行键值对的注入,例子如下:
1 首先在applicationContext.xml中加入:
1 2 3 |
<beans xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> </beans> |
的命名空间,然后
2
1 |
<util:properties id="settings" location="WEB-INF/classes/META-INF/spring/test.properties" /> |
3 创建test.properties
abc=123
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/admin/images") @Controller public class ImageAdminController { private String imageDir; @Value("#{settings['test.abc']}") public void setImageDir(String val) { this.imageDir = val; } } |
这样就将test.abc的值注入了imageDir中了