我有一个简单的类,并希望使用@Autowired从numberHandler对象触发该方法。但是该对象为null。有任何想法吗?
@Component
public class Startup implements UncaughtExceptionHandler {
@Autowired
private MyHandler myHandler;
public static void main(String[] args) {
startup = new Startup();
startup(args);
}
public static void startup(String[] args) {
startup = new Startup();
}
private void start() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
myHandler.run(); //NULL
}
的applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.my.lookup"/>
和实现类:
package com.my.lookup;
@Component
public class MyHandler implements Runnable {
private static Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);
@Override
public void run() {
// do something
}
我是否必须使用ClassPathXmlApplicationContext()在主类中显式定义applicationContext.xml,或者Spring是否可以在类路径中自动识别它?
答案 0 :(得分:1)
问题是您正在实例化不由Spring管理的Startup
类。您需要从Startup
获取Spring管理的ApplicationContext
实例。如下更改主要方法应该有效...
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
startup = context.getBean(Startup.class);
startup.start();
}
private void start() {
myHandler.run();
}