简体   繁体   中英

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. However the object is 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:

<?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?

The problem is you are instantiating the Startup class which is not managed by Spring. You need to get the Startup instance managed by Spring from your ApplicationContext . 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM