1

我有一个简单的类,想使用 @Autowired 从 numberHandler 对象触发方法。但是该对象为空。有任何想法吗?

@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
 }

应用程序上下文.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 是否可以在我的类路径中自动识别它?

4

1 回答 1

1

问题是您正在实例化Startup不受 Spring 管理的类。您需要Startup从您的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();
}
于 2013-04-04T13:42:23.470 回答