org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
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;
}
}