我正在尝试在Spring mvc 4.1.6版本中读取属性文件,但我遇到了一些问题。
分配器一servlet.xml中
hex
我的班级
<context:property-placeholder location="classpath:login.properties"/>
打印值时,我将server_ip设为null。我的login.properties位于src / main / resources文件夹中。
我也尝试了@Value(&#34; $ {login.server_ip}&#34;),但在部署应用程序时遇到了不同的错误。我得到了
@Component
public class UserCheck {
@Value("${server_ip}") String server_ip;
public String isUserPresent(String userName){
System.out.println("server_ip: " + server_ip);
return "";
}
}
还有什么我需要做的吗?
感谢。
修改
我的属性文件如下所示:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name : Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field
我的完整调度程序servlet:
server_ip=192.168.1.1
编辑2:
我的web.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<context:component-scan base-package="com.company"></context:component-scan>
**<context:annotation-config/>**
<mvc:annotation-driven />
<mvc:resources mapping="/**" location="/" />
<context:property-placeholder location="classpath:login.properties"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/" />
<property name = "suffix" value=".jsp" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
This was added for testing**********************
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
</beans>
编辑3:我的控制器类使用@PostConstruct方法
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>test</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:0)
首先,您需要在课程上使用@Configuration
注释。不确定它只适用于@Component
其次,我不知道您的项目类型和设置,但如果您的.properties文件最终在WEB-INF / classes目录中,那么Spring应该可以选择它。
编辑:
您需要将其添加到配置文件<context:annotation-config/>