`

spring3中新增的@value注解

阅读更多
        今天在开发过程中,发现在@Controller层的类,无法像Servicen层的类那样直接通过@Value("${fileUpload.fileName}")方式注入配置值到对象中。
        原因是因为在xml中有如下配置,将配置有@Controller注解的Action类(包名有action)排除掉了。
<context:component-scan base-package="com">
	<context:exclude-filter type="regex" expression=".*\.web\..*" />
	<context:exclude-filter type="regex" expression=".*\.action\..*" />
</context:component-scan>
        后通过如下方法解决:
        在spring 3.0中,可以通过使用@value,对一些如xxx.properties文件中的文件,进行键值对的注入,例子如下:
1.首先在applicationContext.xml中加入: 
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 的命名空间,然后
2.
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations">  
        <list>  
            <value>classpath:test.properties</value>  
        </list>              
    </property>                              
</bean>

3.创建test.properties
   abc=123

4.
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("${abc}") 
    public void setImageDir(String val) {   
        this.imageDir = val;   
    }
}
        这样就将test.abc的值注入了imageDir中了。
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics