Springboot多模块开发三:普通类调用Spring bean对象

在springboot多模块开发过程中,我们有时候需要用到spring提供的bean对象(通过@Autowired 注入),但是在一个普通的java类中使用时,获取不了bean对象,比如我有一个模块是netty,需要用到service模块中的方法,这时候该怎么做呢,
1、在Springboot可以扫描的包下
写一个工具类,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean

package com.xxx.monitoring.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static  T getBean(Class clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static  T getBean(String name,Class clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }


}

2、在Springboot扫描不到的包下
工具类还是和上面一样,只是不需要写Component注解(写了也没用,因为扫描不到),使用@Bean注解,在SpringbootApplication.java类中将SpringUtil注解进

package me.shijunjie.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import me.shijunjie.util.SpringUtil2;

@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer{
    @Bean
    public SpringUtil2 getSpringUtil2() {
        return new SpringUtil2();
    }
    
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

你可能感兴趣的:(Springboot多模块开发三:普通类调用Spring bean对象)