- 创建一个工具类继承ApplicationContextAware
package com.example.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
if(SpringUtil.applicationContext == null) {
SpringUtil.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> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
2、在项目启动类添加工具类的bean
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.example.util.SpringUtil;
@SpringBootApplication
public class AopDemo1Application {
@Bean
public SpringUtil getSpringUtil() {
return new SpringUtil();
}
public static void main(String[] args) {
SpringApplication.run(AopDemo1Application.class, args);
}
}
3、然后创建一个controller类
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.util.SpringUtil;
@Controller
@RequestMapping("/test")
public class TestController {
@ResponseBody
@PostMapping("/name")
public Object tes() {
System.out.println(SpringUtil.getBean("aspectDemo"));
return SpringUtil.getBean("aspectDemo");
}
}
控制台显示