programing

메인 클래스에서 Spring-Boot @Autowired가 null이 됩니다.

magicmemo 2023. 7. 20. 21:50
반응형

메인 클래스에서 Spring-Boot @Autowired가 null이 됩니다.

Sonic Broker Topic(Sonic Broker 토픽)에 연결하여 들어오는 XML 메시지를 수신하려고 합니다.아래와 같은 작업을 수행했습니다.

Application.java

@SpringBootApplication
@ComponentScan({"com.mainpack", "com.msgpack.jms"})
@EnableJms
public class Application extends SpringBootServletInitializer {

@Autowired
private JmsTopicListener jmsTopicListener;

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
}

@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
    try {
        LogService.info(Application.class.getName(), "Starting Service...");
        super.onStartup(servletContext);
        jmsTopicListener.listenMessage();
        LogService.info(Application.class.getName(), "Service Started");
    } catch (Exception ex) {
        LogService.error(this.getClass().getName(), ex);
    }
}

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(Application.class, args);
    LogService.info(Application.class.getName(), "Service Started...");
 }
}

JmsTopicListener.java

@Component
public class JmsTopicListener {

@Autowired
private ApplicationProperties properties;

@Autowired
private MsgListener msgListener;

public void listenMessage() {
    TopicConnectionFactory factory;
    TopicConnection connection = null;
    LogService.info(this.getClass().getName(), "Registering Broker Connection");
    try {
        factory = new progress.message.jclient.TopicConnectionFactory(properties.getBrokerURL());
        connection = factory.createTopicConnection(properties.getUserName(), properties.getPass());

        javax.jms.TopicSession subSession = (TopicSession) connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        javax.jms.Topic topic = subSession.createTopic(properties.getTopicName());
        MessageConsumer subscriber = subSession.createSubscriber(topic);
        subscriber.setMessageListener(msgListener);
        connection.start();
        LogService.info(this.getClass().getName(), "Broker connected");
    } catch (Exception ex) {
        LogService.error(this.getClass().getName(), ex);
    }
 }
}

MsgListener.java

@Component
public class MsgListener implements MessageListener {

@Override
public void onMessage(Message msg) {
    if (msg instanceof XMLMessage) {
        try {
            XMLMessage m = (XMLMessage) msg;
            if (m.getText().contains("Applications")) {
                LogService.info(this.getClass().getName(), "Recieved A Applications Message");
            } else {
                LogService.info(this.getClass().getName(), "Recieved Message Does not contain Applications Tag");
            }
        } catch (Exception ex) {
            LogService.info(this.getClass().getName(), "Exception: " + ex.getMessage());
        }
    }
 }
}

이 코드를 실행할 때 라인에서 nullPointer를 받습니다.jmsTopicListener.listenMessage()Application.java.

내가 여기서 무슨 실수를 했습니까?제가 이것을 개선할 수 있는 방법이 있을까요? (즉, 작업을 코드를 더 적게 사용하여 완료하는 것입니다.)

참고: com.mainpack에는 클래스가 있습니다.Application.java그리고.ApplicationProp.javacom.msgpack.jms는JmsTopicListener.java그리고.MsgListner.java

로거 오류:

ERROR [2015-07-14 14:34:52] [com.mainpack.Application] [localhost-startStop-1] - [Exception: ]java.lang.NullPointerException
    at com.mainpack.Application.onStartup(Application.java:33)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5156)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1768)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

onStartup응용 프로그램의 수명 주기 초기에 서블릿 컨테이너에 의해 호출되며 Spring Boot가 아닌 서블릿 컨테이너에 의해 생성된 클래스의 인스턴스에서 호출됩니다.이것이 이유입니다.jmsTopicListener이라null.

우선순위를 정하는 것보다onStartup주석이 달린 방법을 사용할 수 있습니다.@PostConstructSpring이 인스턴스를 만들면 이를 Spring이라고 부릅니다.Application 모든 종속성을 주입했습니다.

@SpringBootApplication
@ComponentScan({"com.mainpack", "com.msgpack.jms"})
@EnableJms
public class Application extends SpringBootServletInitializer {

    @Autowired
    private JmsTopicListener jmsTopicListener;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @PostConstruct
    public void listen() { 
        jmsTopicListener.listenMessage();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        LogService.info(Application.class.getName(), "Service Started...");
    }
}

그냥 추가

@PostConstruct

메소드를 실행하고 이 메소드의 코드를 실행하면 작동합니다.

언급URL : https://stackoverflow.com/questions/31399924/spring-boot-autowired-in-main-class-is-getting-null

반응형