您的位置:首页 > 编程语言 > Java开发

spring使用@value关于<context:component-scan base-package=”com.baidu” />的一个错误

2018-03-12 00:18 597 查看
最近写了一个项目中使用了spring的@value,将值从*.properties中取出来,注入给某个变量.
我是给一个参数注入Integer,Long这样的类型,但是传过来的一直是String
加入*.properties文件里有个这样的参数,student=1
1.
@value(“${student}”)
private Integer user;
这样会报异常

Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "${student}"
看着是传过来的是String类型,用Integer接收报错,所以决定用String接收,然后在代码里面转换。
2.
接着用String接收,注入的却是@value里面的数,比如传过来的student=1
@value(“${student}”)
private String user;
user应该等于1,但是等于${student}
 
一般来说使用分为以下几个步骤:
1.
在准确位置创建一个properties文件,里面写上你想注入的文件参数

student=1


2.配置文件





创建一个applicationContext-任意什么名字.xml

注意下面

<!--配置包扫描器-->
<context:component-scan base-package="com.baidu"/>
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:conf/*.properties" />
注意这里

路径必须正确。

3.

这个xml文件需要被web.xml的spring容器加载

<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class></listener-class>
</listener>

而不是下面这个

<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>xmall-front-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


4.直接在需要注入的变量,方法上面写

@value(“${student}”)就可以了

 

最后,这次上面那两个问题是怎么回事,配置文件applicationContext-dao.xml是被spring容器加载的,springmvc-xml的文件是被springmvc的前端控制器加载的,而我在这两个里面都写了

<context:component-scan base-package="com.baidu" />


也就是扫描包这个。然后就出现了上面的两个错误。

现在需要把spingmvc.xml里面的删除,不要拘泥于文件名字,就是把  被springmvc前端控制器加载 的那个配置文件,里面的扫描包配置删除,重新启动就没错了。

根本原因也不知道为什么,先记下了,有空了看看源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐