springboot在工具类中注入bean(ApplicationContextAware)解析

熊孩纸 阅读:465 2021-04-01 11:29:55 评论:0

1、创建测试类1(MyService1.java)

package com.jeff.service; 
 
import org.springframework.stereotype.Service; 
 
@Service 
public class MyService1 {
    
 
	public void save() {
    
		System.out.println(">>>>>>>>>>>>>>> MyService1执行save <<<<<<<<<<<<<<<"); 
	} 
 
} 
 

2、创建测试类2(MyService2.java)

package com.jeff.service; 
 
import org.springframework.stereotype.Service; 
 
@Service 
public class MyService2 {
    
 
	public void save() {
    
		System.out.println(">>>>>>>>>>>>>>> MyService2执行save <<<<<<<<<<<<<<<"); 
	} 
 
} 
 

3、创建工具类(SpringUtil.java)

package com.jeff.utils; 
 
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 context; 
 
	@Override 
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
		if (context == null) {
    
			context = applicationContext; 
		} 
	} 
 
	// 获得applicationContext 
	public static ApplicationContext getApplicationContext() throws Exception {
    
		isContext(); 
		return context; 
	} 
 
	// 通过class获取Bean 
	public static <T> T getBean(Class<T> clazz) throws Exception {
    
		return getApplicationContext().getBean(clazz); 
	} 
 
	// 通过name获取 Bean 
	public static Object getBean(String name) throws Exception {
    
		return getApplicationContext().getBean(name); 
	} 
 
	// 判断application是否为空 
	public static void isContext() throws Exception {
    
		if (context == null) {
    
			throw new Exception("application未注入"); 
		} 
	} 
 
} 
 

4、创建工具类(MyUtil.java)

package com.jeff.utils; 
 
import com.jeff.service.MyService1; 
import com.jeff.service.MyService2; 
 
public class MyUtil {
    
 
	public static void getBean() throws Exception {
    
		SpringUtil.getBean(MyService1.class).save(); 
	} 
 
	public static void getBeanByName(String name) throws Exception {
    
		((MyService2) SpringUtil.getBean(name)).save(); 
	} 
 
} 
 

5、创建测试类(MyController.java)

package com.jeff.controller; 
 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
 
import com.jeff.utils.MyUtil; 
 
@RestController 
public class MyController {
    
 
	@RequestMapping("myTest") 
	public String myTest() {
    
		try {
    
			MyUtil.getBean(); 
			MyUtil.getBeanByName("myService2"); 
		} catch (Exception e) {
    
			e.printStackTrace(); 
		} 
		return "success"; 
	} 
 
} 
 

6、控制台输出结果
在这里插入图片描述

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

我的关注

全民解析

搜索
排行榜
关注我们