SpringBoot?如何從容器中獲取對(duì)象
如何從容器中獲取對(duì)象
有時(shí)候在項(xiàng)目中,我們會(huì)自己創(chuàng)建一些類,類中需要使用到容器中的一些類。方法是新建類并實(shí)現(xiàn)ApplicationContextAware 接口,在類中建立靜態(tài)對(duì)象 ApplicationContext 對(duì)象,這個(gè)對(duì)象就如同xml配置中的 applicationContext.xml,容器中類都可以獲取到。
例如@Service、 @Component、@Repository、@Controller 、@Bean 標(biāo)注的類都能獲取到。
/**
* 功能描述:Spring Bean 管理類
*
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
/**
* 上下文對(duì)象實(shí)例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 獲取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通過name獲取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通過class獲取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
try{
return getApplicationContext().getBean(clazz);
}catch (Exception e){
return null;
}
}
/**
* 通過name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
SpringBoot中的容器
容器功能
1、組件添加
(1)主要注解
@Configuration
告訴SpringBoot這是一個(gè)配置類 == 配置文件
注意:spring5.2以后@Configuration多了一個(gè)屬性proxyBeanMethods,默認(rèn)為true
@Configuration(proxyBeanMethods = true)
proxyBeanMethods:代理bean的方法Full(proxyBeanMethods = true)、【保證每個(gè)@Bean方法被調(diào)用多少次返回的組件都是單實(shí)例的】 外部無論對(duì)配置類中的這個(gè)組件注冊(cè)方法調(diào)用多少次獲取的都是之前注冊(cè)容器中的單實(shí)例對(duì)象Lite(proxyBeanMethods = false)【每個(gè)@Bean方法被調(diào)用多少次返回的組件都是新創(chuàng)建的】- 組件依賴必須使用Full模式默認(rèn)。其他默認(rèn)是否Lite模式
● Full模式與Lite模式
○ 最佳實(shí)戰(zhàn)
■ 配置 類組件之間無依賴關(guān)系用Lite模式加速容器啟動(dòng)過程,減少判斷
■ 配置類組件之間有依賴關(guān)系,方法會(huì)被調(diào)用得到之前單實(shí)例組件,用Full模式
@Bean
- 給容器中添加組件。以方法名作為組件的id。返回類型就是組件類型。返回的值,就是組件在容器中的實(shí)例
- 配置類里面使用@Bean標(biāo)注在方法上給容器注冊(cè)組件,默認(rèn)是單實(shí)例的
- 配置類本身也是組件
(2) 基本使用
bean包:
Pet類:
/**
* 寵物
*/
public class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Pet(String name) {
this.name = name;
}
public Pet() {
}
@Override
public String toString() {
return "Pet{" +
"name='" + name + '\'' +
'}';
}
}
User類:
/*
用戶
*/
public class User {
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
config包:
MyConfig類
@Configuration(proxyBeanMethods = false)//告訴Spring這是一個(gè)配置類
public class MyConfig {
@Bean//給容器中添加組件。以方法名作為組件的id。返回類型就是組件類型。返回的值,就是組件在容器中的實(shí)例
public User user01(){
return new User("zhangsan",18);
}
@Bean("tom")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
controller包:
MainApplication類
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com")
public class MainApplication {
public static void main(String[] args) {
//1、返回我們IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的組件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
//3、從容器中獲取組件
MyConfig bean = run.getBean(MyConfig.class);
System.out.println(bean);
//如果@Configuration(proxyBeanMethods = true)代理對(duì)象調(diào)用方法。SpringBoot總會(huì)檢查這個(gè)組件是否在容器中有。
//保持組件單實(shí)例
User user = bean.user01();
User user1 = bean.user01();
System.out.println("組件為:"+(user == user1));
}
}
結(jié)果

(3)補(bǔ)充 @Import
給容器導(dǎo)入一個(gè)組件
必須寫在容器中的組件上
* @Import({User.class, DBHelper.class})
* 給容器中自動(dòng)創(chuàng)建出這兩個(gè)類型的組件、默認(rèn)組件的名字就是全類名
*
*
*
*/
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告訴SpringBoot這是一個(gè)配置類 == 配置文件
public class MyConfig {
}
@Configuration測(cè)試代碼如下
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com")
public class MainApplication {
public static void main(String[] args) {
//1、返回我們IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的組件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
//3、從容器中獲取組件
MyConfig bean = run.getBean(MyConfig.class);
System.out.println(bean);
//如果@Configuration(proxyBeanMethods = true)代理對(duì)象調(diào)用方法。SpringBoot總會(huì)檢查這個(gè)組件是否在容器中有。
//保持組件單實(shí)例
User user = bean.user01();
User user1 = bean.user01();
System.out.println("組件為:"+(user == user1));
//5、獲取組件
String[] beanNamesForType = run.getBeanNamesForType(User.class);
System.out.println("======");
for (String s : beanNamesForType) {
System.out.println(s);
}
DBHelper bean1 = run.getBean(DBHelper.class);
System.out.println(bean1);
}
}

@Conditional
條件裝配:滿足Conditional指定的條件,則進(jìn)行組件注入

ConditionalOnBean:當(dāng)容器中存在指定的bean組件時(shí)才干某些事情ConditionalOnMissingBean:當(dāng)容器中不存在指定的bean組件時(shí)才干某些事情ConditionalOnClass:當(dāng)容器中有某個(gè)類時(shí)才干某些事情ConditionalOnResource:當(dāng)項(xiàng)目的類路徑存在某個(gè)資源時(shí),才干什么事
=====================測(cè)試條件裝配==========================
@Configuration(proxyBeanMethods = false) //告訴SpringBoot這是一個(gè)配置類 == 配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
@Bean //給容器中添加組件。以方法名作為組件的id。返回類型就是組件類型。返回的值,就是組件在容器中的實(shí)例
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user組件依賴了Pet組件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom22")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
測(cè)試:
public static void main(String[] args) {
//1、返回我們IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的組件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
boolean tom = run.containsBean("tom");
System.out.println("容器中Tom組件:"+tom);
boolean user01 = run.containsBean("user01");
System.out.println("容器中user01組件:"+user01);
boolean tom22 = run.containsBean("tom22");
System.out.println("容器中tom22組件:"+tom22);
}

2、原生配置文件引入(xml文件引入)
@ImportResource
導(dǎo)入資源
@ImportResource("classpath:beans.xml")//導(dǎo)入spring的配置文件
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false)//告訴Spring這是一個(gè)配置類
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="haha" class="com.atguigu.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.atguigu.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
測(cè)試
======================測(cè)試=================
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true

3、配置綁定
如何使用Java讀取到properties文件中的內(nèi)容,并且把它封裝到JavaBean中,以供隨時(shí)使用;
(1) @Component + @ConfigurationProperties
properties文件

/**
* 只有在容器中的組件,才會(huì)擁有SpringBoot提供的強(qiáng)大功能
*/
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
(2) @EnableConfigurationProperties + @ConfigurationProperties
@Configuration(proxyBeanMethods = false) //告訴SpringBoot這是一個(gè)配置類 == 配置文件
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
//@EnableConfigurationProperties(Car.class)
//1、開啟Car配置綁定功能
//2、把這個(gè)Car這個(gè)組件自動(dòng)注冊(cè)到容器中
public class MyConfig {
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
MVC頁面之間參數(shù)傳遞實(shí)現(xiàn)過程圖解
這篇文章主要介紹了MVC頁面之間參數(shù)傳遞實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
springboot+springJdbc+postgresql 實(shí)現(xiàn)多數(shù)據(jù)源的配置
本文主要介紹了springboot+springJdbc+postgresql 實(shí)現(xiàn)多數(shù)據(jù)源的配置,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
SpringBoot實(shí)戰(zhàn)教程之新手入門篇
Spring Boot使我們更容易去創(chuàng)建基于Spring的獨(dú)立和產(chǎn)品級(jí)的可以"即時(shí)運(yùn)行"的應(yīng)用和服務(wù),下面這篇文章主要給大家介紹了關(guān)于SpringBoot實(shí)戰(zhàn)教程之入門篇的相關(guān)資料,需要的朋友可以參考下2022-03-03

