Springboot @Autowired 無法注入問題


特別提醒:一定要注意文件結構

  WebappApplication 一定要在包的最外層,否則Spring無法對所有的類進行托管,會造成@Autowired 無法注入。

1.  添加工具類獲取在 Spring 中托管的 Bean

  (1)工具類

package com.common;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @program: IPC_1P
 * @description: 獲取在spring中托管的bean
 * @author: johnny
 * @create: 2018-08-03 16:24
 **/
public class SpringContextUtil {
    private static ApplicationContext applicationContext; // Spring應用上下文

    // 下面的這個方法上加了@Override注解,原因是繼承ApplicationContextAware接口是必須實現的方法

    public static void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static Object getBean(String name, Class requiredType)
            throws BeansException {

        return applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }

    public static Class getType(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }

    public static String[] getAliases(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }
}

  (2)使用

    1)程序啟動時,實例化 SpringContextUtil

@SpringBootApplication
public class WebappApplication {

    private static ApplicationContext applicationContext;
    public static void main(String[] args) {
        applicationContext = SpringApplication.run(WebappApplication.class, args);

        //
        SpringContextUtil springContextUtil = new SpringContextUtil();
        springContextUtil.setApplicationContext(applicationContext);

        System.out.println("服務器啟動測試!");
}

 

    2)在使用 @Service 的方法中,通過@Autowired 注入,使用SpringcontexUtil 獲取Bean上下文

@Autowired
    SenderService senderService;

public class Package_State  {

    @Autowired
    SenderService senderService;
    
    @Component
    private Package_State() {
        senderService = (SenderService)SpringContextUtil.getBean("senderService");
    }
}

 

Java 初學,原理理解不很透徹,只針對遇到的問題進行記錄,隨着學習的深入隨時修改


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM