特別提醒:一定要註意文件結構 WebappApplication 一定要在包的最外層,否則Spring無法對所有的類進行托管,會造成@Autowired 無法註入。 1. 添加工具類獲取在 Spring 中托管的 Bean (1)工具類 (2)使用 1)程式啟動時,實例化 SpringContext ...
特別提醒:一定要註意文件結構
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 初學,原理理解不很透徹,只針對遇到的問題進行記錄,隨著學習的深入隨時修改