[英]How to @autowire implementation of the class from a jar file?
I have a simple class and would like to use @Autowired to trigger the method from numberHandler object. 我有一个简单的类,想使用@Autowired从numberHandler对象触发该方法。 However the object is null.
但是,该对象为null。 Any ideas?
有任何想法吗?
@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: 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"/>
and the implementation class: 和实现类:
package com.my.lookup;
@Component
public class MyHandler implements Runnable {
private static Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);
@Override
public void run() {
// do something
}
Do I have to explicit define applicationContext.xml in main class with ClassPathXmlApplicationContext() or is there way for Spring to automatically recognize it in my classpath? 我是否必须使用ClassPathXmlApplicationContext()在主类中显式定义applicationContext.xml,或者Spring是否有办法在我的类路径中自动识别它?
The problem is you are instantiating the Startup
class which is not managed by Spring. 问题是您正在实例化不受Spring管理的
Startup
类。 You need to get the Startup
instance managed by Spring from your ApplicationContext
. 您需要从
ApplicationContext
获取由Spring管理的Startup
实例。 Changing your main method as follows should work... 如下更改主要方法应该可以...
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
startup = context.getBean(Startup.class);
startup.start();
}
private void start() {
myHandler.run();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.