如何在非Spring管理的类中使用Spring加载的bean

时间:2023-03-09 22:20:08
如何在非Spring管理的类中使用Spring加载的bean
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

如何在非Spring管理的类中使用Spring加载的bean

package com.example.demo;

public class Person {
private String name; public Person() {
System.out.println("person init ..");
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
package com.example.demo;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; public class ContextUtil{ public ContextUtil () { } private static ApplicationContext applicationContext = null; public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ContextUtil.applicationContext = applicationContext;
} public static Object getObject(String beanName) {
if (applicationContext == null) {
throw new RuntimeException("applicationContext is null");
}
return applicationContext.getBean(beanName);
}
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; @SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
ContextUtil.setApplicationContext(context); // 在这里把加载好的ApplicationContext设置到静态类中,以后通过这个类取Spring容器中的bean

Person person = (Person)ContextUtil.getObject("p");
System.out.println(person);
} @Bean(name = "p")
public Person person() {
Person person = new Person();
person.setName("小明");
return person;
} }