我打算在Spring DI中使用logger(带有slf4j的log4J)。
我正在尝试使用DI初始化主记录器类并在测试类中自动装配该实例。 但是那个实例总是无效的。我不确定我做错了什么。 请注意其在IBM WAS 6.1上部署的Web应用程序。
这就是我正在做的事情
所有课程都在 com.test 包中。
@Repository
public class TestLogger
{
@Autowired
MainLogger error; // this instance of Mainlogger is always null
//if **MainLogger error = new MainLogger();** is used this is working fine!!
public void test(){
error.logerror("test"); //null pointer here
}
}
MainLogger Class
public class MainLogger {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(MainLogger.class);
String str = "Logger check check";
logger.info(str);
}
public void loginfo(String para)
{
Logger logger = LoggerFactory.getLogger(VpayCoreLogger.class);
logger.info(para);
}
public void logdebug(String para)
{
Logger logger = LoggerFactory.getLogger(VpayCoreLogger.class);
logger.debug(para);
}
public void logerror(String para)
{
Logger logger = LoggerFactory.getLogger(VpayCoreLogger.class);
logger.error(para);
}
}
}
应用程序上下文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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<bean id="error" class="com.test.MainLogger">
</bean>
<context:component-scan base-package="com.test"/>
</beans>
WEB XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>testApp</display-name>
<welcome-file-list>
<welcome-file>testDAO.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
答案 0 :(得分:0)
使用TestLogger
注释@Component
以使其成为bean。否则它将不会被组件扫描拾取,使其不符合自动装配/ DI的条件。
@Component
public class TestLogger
{
//code goes here
}
答案 1 :(得分:0)
不确定它的答案是否正确,但我还是以某种方式工作了。 问题在于使用setter或Constructor自动化字段。
@Repository
public class TestLogger
{
private static MainLogger error;
@Autowired
public TestLogger(MainLogger error)
{
this.error=error;
}
public TestLogger()
{
}
public void test(){
error.logerror("test");
}
}