1

シンプルなクラスがあり、@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 がクラスパスでそれを自動的に認識する方法はありますか?

4

1 に答える 1

1

問題はStartup、Spring によって管理されていないクラスをインスタンス化していることです。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();
}
于 2013-04-04T13:42:23.470 に答える