溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot怎么從容器中獲取對(duì)象

發(fā)布時(shí)間:2022-08-23 14:34:29 來(lái)源:億速云 閱讀:223 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容介紹了“SpringBoot怎么從容器中獲取對(duì)象”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

如何從容器中獲取對(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;
    }
    /**
     * 通過(guò)name獲取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    /**
     * 通過(guò)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;
        }
    }
    /**
     * 通過(guò)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í)例的】 外部無(wú)論對(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)

■ 配置 類組件之間無(wú)依賴關(guān)系用Lite模式加速容器啟動(dòng)過(guò)程,減少判斷

■ 配置類組件之間有依賴關(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é)果

SpringBoot怎么從容器中獲取對(duì)象

(3)補(bǔ)充 @Import

給容器導(dǎo)入一個(gè)組件

必須寫(xiě)在容器中的組件上

 * @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);
    }
}

SpringBoot怎么從容器中獲取對(duì)象

@Conditional

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

SpringBoot怎么從容器中獲取對(duì)象

  • 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);
    }

SpringBoot怎么從容器中獲取對(duì)象

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

SpringBoot怎么從容器中獲取對(duì)象

3、配置綁定

如何使用Java讀取到properties文件中的內(nèi)容,并且把它封裝到JavaBean中,以供隨時(shí)使用;

(1) @Component + @ConfigurationProperties

properties文件

SpringBoot怎么從容器中獲取對(duì)象

/**
 * 只有在容器中的組件,才會(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、開(kāi)啟Car配置綁定功能
//2、把這個(gè)Car這個(gè)組件自動(dòng)注冊(cè)到容器中
public class  MyConfig {

“SpringBoot怎么從容器中獲取對(duì)象”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI