最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot?如何從容器中獲取對象

 更新時間:2022年08月23日 11:27:27   作者:飄零未歸人  
這篇文章主要介紹了SpringBoot?如何從容器中獲取對象,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

如何從容器中獲取對象

有時候在項目中,我們會自己創(chuàng)建一些類,類中需要使用到容器中的一些類。方法是新建類并實(shí)現(xiàn)ApplicationContextAware 接口,在類中建立靜態(tài)對象 ApplicationContext 對象,這個對象就如同xml配置中的 applicationContext.xml,容器中類都可以獲取到。

例如@Service、 @Component、@Repository、@Controller 、@Bean 標(biāo)注的類都能獲取到。

/**
 * 功能描述:Spring Bean 管理類
 *
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    /**
     * 上下文對象實(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這是一個配置類 == 配置文件

注意:spring5.2以后@Configuration多了一個屬性proxyBeanMethods,默認(rèn)為true

@Configuration(proxyBeanMethods = true)
  • proxyBeanMethods:代理bean的方法
  • Full(proxyBeanMethods = true)、【保證每個@Bean方法被調(diào)用多少次返回的組件都是單實(shí)例的】 外部無論對配置類中的這個組件注冊方法調(diào)用多少次獲取的都是之前注冊容器中的單實(shí)例對象
  • Lite(proxyBeanMethods = false)【每個@Bean方法被調(diào)用多少次返回的組件都是新創(chuàng)建的】
  • 組件依賴必須使用Full模式默認(rèn)。其他默認(rèn)是否Lite模式

● Full模式與Lite模式

○ 最佳實(shí)戰(zhàn)

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

■ 配置類組件之間有依賴關(guān)系,方法會被調(diào)用得到之前單實(shí)例組件,用Full模式

@Bean

  • 給容器中添加組件。以方法名作為組件的id。返回類型就是組件類型。返回的值,就是組件在容器中的實(shí)例
  • 配置類里面使用@Bean標(biāo)注在方法上給容器注冊組件,默認(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這是一個配置類
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)代理對象調(diào)用方法。SpringBoot總會檢查這個組件是否在容器中有。
        //保持組件單實(shí)例
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println("組件為:"+(user == user1));
    }
}

結(jié)果

(3)補(bǔ)充 @Import

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

必須寫在容器中的組件上

 * @Import({User.class, DBHelper.class})
 *      給容器中自動創(chuàng)建出這兩個類型的組件、默認(rèn)組件的名字就是全類名
 *
 *
 *
 */
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告訴SpringBoot這是一個配置類 == 配置文件
public class MyConfig {
}

@Configuration測試代碼如下

@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)代理對象調(diào)用方法。SpringBoot總會檢查這個組件是否在容器中有。
        //保持組件單實(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組件時才干某些事情
  • ConditionalOnMissingBean:當(dāng)容器中不存在指定的bean組件時才干某些事情
  • ConditionalOnClass:當(dāng)容器中有某個類時才干某些事情
  • ConditionalOnResource:當(dāng)項目的類路徑存在某個資源時,才干什么事
=====================測試條件裝配==========================
@Configuration(proxyBeanMethods = false) //告訴SpringBoot這是一個配置類 == 配置文件
//@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");
    }
}

測試:

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這是一個配置類
@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>

測試

======================測試=================
        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中,以供隨時使用;

(1) @Component + @ConfigurationProperties

properties文件

/**
 * 只有在容器中的組件,才會擁有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這是一個配置類 == 配置文件
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
//@EnableConfigurationProperties(Car.class)
//1、開啟Car配置綁定功能
//2、把這個Car這個組件自動注冊到容器中
public class  MyConfig {

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java中區(qū)別.toString() ,(String),valueOf()方法

    Java中區(qū)別.toString() ,(String),valueOf()方法

    這篇文章主要介紹了Java中區(qū)別.toString() ,(String),valueOf()方法,需要的朋友可以參考下
    2017-01-01
  • SpringBoot中使用Session共享實(shí)現(xiàn)分布式部署的示例代碼

    SpringBoot中使用Session共享實(shí)現(xiàn)分布式部署的示例代碼

    這篇文章主要介紹了SpringBoot中使用Session共享實(shí)現(xiàn)分布式部署的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Java?NIO實(shí)現(xiàn)聊天系統(tǒng)

    Java?NIO實(shí)現(xiàn)聊天系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java?NIO實(shí)現(xiàn)聊天系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • SpringBoot使用Apache?Tika檢測敏感信息

    SpringBoot使用Apache?Tika檢測敏感信息

    Apache?Tika?是一個功能強(qiáng)大的內(nèi)容分析工具,它能夠從多種文件格式中提取文本、元數(shù)據(jù)以及其他結(jié)構(gòu)化信息,下面我們來看看如何使用Apache?Tika檢測敏感信息從而實(shí)現(xiàn)數(shù)據(jù)泄露防護(hù)吧
    2025-01-01
  • Spring boot+VUE實(shí)現(xiàn)token驗(yàn)證的示例代碼

    Spring boot+VUE實(shí)現(xiàn)token驗(yàn)證的示例代碼

    本文詳細(xì)介紹了使用Vue和SpringBoot實(shí)現(xiàn)token認(rèn)證的方法,包括前后端交互流程、后端依賴導(dǎo)入、token工具類、攔截器、跨域處理、前端路由守衛(wèi)、請求攔截器等內(nèi)容,具有一定的參考價值,感興趣的可以了解一下
    2024-10-10
  • Spring使用@Filter注解創(chuàng)建自定義過濾器

    Spring使用@Filter注解創(chuàng)建自定義過濾器

    Spring 中鮮為人知但非常有用的注解之一是 @Filter,它支持自定義過濾器,下面我們就來深入研究一下如何使用 Spring 的 @Filter 注解來創(chuàng)建自定義過濾器吧
    2023-11-11
  • Spring@Value屬性注入使用方法解析

    Spring@Value屬性注入使用方法解析

    這篇文章主要介紹了Spring@Value屬性注入使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • Java實(shí)現(xiàn)對視頻進(jìn)行截圖的方法【附ffmpeg下載】

    Java實(shí)現(xiàn)對視頻進(jìn)行截圖的方法【附ffmpeg下載】

    這篇文章主要介紹了Java實(shí)現(xiàn)對視頻進(jìn)行截圖的方法,結(jié)合實(shí)例形式分析了Java使用ffmpeg針對視頻進(jìn)行截圖的相關(guān)操作技巧,并附帶ffmpeg.exe文件供讀者下載使用,需要的朋友可以參考下
    2018-01-01
  • SpringBoot多環(huán)境打包與配置文件排除實(shí)踐記錄

    SpringBoot多環(huán)境打包與配置文件排除實(shí)踐記錄

    本文介紹了SpringBoot項目多環(huán)境打包與配置文件排除實(shí)踐,包括多環(huán)境配置的實(shí)現(xiàn)方法、打包時排除配置文件的方法以及動態(tài)加載外部配置文件的最佳實(shí)踐,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • 解決springboot利用ConfigurationProperties注解配置數(shù)據(jù)源無法讀取配置信息問題

    解決springboot利用ConfigurationProperties注解配置數(shù)據(jù)源無法讀取配置信息問題

    今天在學(xué)習(xí)springboot利用ConfigurationProperties注解配置數(shù)據(jù)源的使用遇到一個問題無法讀取配置信息,發(fā)現(xiàn)全部為null,糾結(jié)是哪里出了問題呢,今天一番思考,問題根源找到,下面把我的解決方案分享到腳本之家平臺,感興趣的朋友一起看看吧
    2021-05-05

最新評論

丹江口市| 和龙市| 新郑市| 玛沁县| 墨竹工卡县| 潜山县| 芜湖县| 崇信县| 弥勒县| 昆山市| 肃南| 京山县| 赤壁市| 金寨县| 临桂县| 社旗县| 雷州市| 绥滨县| 常山县| 义马市| 马关县| 儋州市| 茂名市| 双辽市| 康保县| 喀喇| 读书| 横山县| 应城市| 炎陵县| 浦江县| 鄂温| 安乡县| 尤溪县| 太白县| 石棉县| 醴陵市| 收藏| 江川县| 龙州县| 宜兰县|