1
我有一个简单的类,并希望使用@Autowired从numberHandler对象触发该方法。但是该对象为空。有任何想法吗?如何从jar文件@autowire类的实现?
@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有办法在我的classpat中自动识别它H?
它的工作。谢谢!关于第二个问题:我是否必须使用ClassPathXmlApplicationContext()在主类中明确定义applicationContext.xml,还是有办法让Spring在我的类路径中自动识别它? – luksmir 2013-04-05 07:00:21
您需要像初始化应用程序上下文一样,在普通的java应用程序中没有自动方式。请将答案标记为已接受,因为它解决了您的问题。 – hyness 2013-04-09 13:58:31
感谢您的回答。 – luksmir 2013-04-10 07:11:19