Springboot控制反轉(zhuǎn)與Bean對(duì)象的方法
1 控制反轉(zhuǎn)
1.1 什么是控制反轉(zhuǎn)
控制反轉(zhuǎn)(IoC)是一種設(shè)計(jì)原則,它將對(duì)象的創(chuàng)建、依賴(lài)注入和生命周期管理等責(zé)任從應(yīng)用程序代碼中轉(zhuǎn)移到框架或容器中
1.2 SpringBoot中的控制反轉(zhuǎn)
Spring框架通過(guò)IoC容器來(lái)管理Bean的生命周期和依賴(lài)關(guān)系,從而實(shí)現(xiàn)控制反轉(zhuǎn)
2 Ioc容器對(duì)Bean的管理
2.1 什么是Bean對(duì)象?
在Spring框架中,Bean是一個(gè)由Spring IoC容器管理的對(duì)象。Bean的創(chuàng)建、初始化、依賴(lài)注入以及銷(xiāo)毀都由Spring容器負(fù)責(zé)。Bean可以是任何Java對(duì)象,通常是一個(gè)POJO(Plain Old Java Object)。
2.2 Bean的注冊(cè)過(guò)程
2.2.1 掃描Bean
- 在Spring應(yīng)用中,手動(dòng)配置每個(gè)Bean會(huì)非常繁瑣,尤其是在大型項(xiàng)目中。@ComponentScan通過(guò)自動(dòng)掃描和注冊(cè)Bean,簡(jiǎn)化了這一過(guò)程,使開(kāi)發(fā)者能夠?qū)W⒂跇I(yè)務(wù)邏輯。
- 在Spring Boot應(yīng)用中,@ComponentScan通常與@SpringBootApplication注解一起使用。@SpringBootApplication注解包含了@ComponentScan,默認(rèn)會(huì)掃描主類(lèi)所在包及其子包。
- 下面例子中,Spring會(huì)掃描com.example.service和com.example.repository包及其子包下的所有組件。
@Configuration
@ComponentScan(basePackages = {"com.example.service", "com.example.repository"})
public class AppConfig {
}2.2.2 定義Bean
使用@Component及其派生注解:Spring支持通過(guò)@ComponentScan自動(dòng)掃描并注冊(cè)Bean。常用的注解包括:
@Component:通用注解,用于標(biāo)記任意類(lèi)為 Bean。
@Service:用于標(biāo)記服務(wù)層的類(lèi)。
@Repository:用于標(biāo)記數(shù)據(jù)訪問(wèn)層的類(lèi)。
@Controller:用于標(biāo)記控制器層的類(lèi)。
@Configuration:用于標(biāo)記配置類(lèi)。使用@Bean注解:在配置類(lèi)中,可以使用@Bean注解顯式定義Bean。@Bean通常用于定義第三方庫(kù)中的類(lèi)或需要自定義配置的Bean。
@Configuration// 配置注解
public class CommonConfig {
/**
* @Bean注解標(biāo)注的方法會(huì)被 Spring容器調(diào)用,并將返回值注冊(cè)為一個(gè) Bean
*/
@Bean
public Country country(){
return new Country();
}
/**
* 默認(rèn)情況下,Bean 的名稱(chēng)是方法名。你可以通過(guò)name或value屬性指定Bean的名稱(chēng)。
*/
@Bean(name = "customService")
public MyService myService() {
//Bean 的名稱(chēng)為 customService,而不是默認(rèn)的 myService。
return new MyService();
}
}3.基于 XML 配置的注冊(cè):早期的 Spring 版本中,Bean 通常通過(guò) XML 配置文件注冊(cè)。雖然現(xiàn)在推薦使用注解,但 XML 配置仍然支持
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注冊(cè)一個(gè) Bean -->
<bean id="myService" class="com.example.MyService"/>
</beans>條件化的 Bean 注冊(cè):可以結(jié)合條件注解(如 @ConditionalOnProperty、@ConditionalOnClass 等)實(shí)現(xiàn)條件化的 Bean 注冊(cè)
CommonConfig.java
@Configuration
public class CommonConfig {
/**
* 使用@ConditionalOnProperty 條件注入:配置文件中前綴是province,屬性名為name的值若是wfs,則聲明此Bean
* @ConditionalOnMissingBean 當(dāng)不存在當(dāng)前類(lèi)型的bean時(shí),才聲明該bean
* @ConditionalOnClass 當(dāng)classpath下存在指定類(lèi)時(shí),才聲明該bean
*/
@ConditionalOnProperty(prefix = "province",name = "name" ,havingValue = "wfs")
@ConditionalOnMissingBean
@ConditionalOnClass(name = "com.wfs.config.CommonConfig")
public Province province(@Value("${province.name}") String name,
@Value("${province.direction}") String direction) {
Province province = new Province();
province.setName(name);
province.setDirection(direction);
return province;
}
}2.3 @import注解
@Import注解用于將其他配置類(lèi)或組件引入到當(dāng)前配置類(lèi)中。它提供了一種模塊化的方式來(lái)組織Spring應(yīng)用的配置,避免將所有配置集中在一個(gè)類(lèi)中。優(yōu)先使用@ComponentScan:如果可以通過(guò)@ComponentScan掃描到的類(lèi),盡量使用@ComponentScan而不是@Import。如下面的例子:
啟動(dòng)類(lèi)
/*
1@Import 可以標(biāo)注在 @Configuration 類(lèi)或 @Component 類(lèi)上,用于導(dǎo)入其他配置類(lèi)或組件類(lèi)
2@Import 可以同時(shí)導(dǎo)入多個(gè)配置類(lèi)。
3@Import 還可以導(dǎo)入實(shí)現(xiàn)了 ImportSelector 接口的類(lèi),用于動(dòng)態(tài)選擇需要導(dǎo)入的配置類(lèi)或組件類(lèi)
*/
@Import(com.wfs.config.CommonImportSeletor.class)//使用@Import導(dǎo)入ImportSelector
//@Import(com.wfs.config.CommonConfig.class)
@SpringBootApplication
public class SpringbootBeanRegisterApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringbootBeanRegisterApplication.class, args);//獲取ioc容器
Country country = context.getBean(Country.class);//獲取bean
System.out.println(country);
System.out.println(context.getBean("aa"));CommonImportSeletor.java
/**
* @ImportSelector:導(dǎo)入選擇器
* 作用:導(dǎo)入指定配置類(lèi)
*/
public class CommonImportSeletor implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.wfs.config.CommonConfig"};
}
}2.4 Bean的注冊(cè)順序
- 配置類(lèi):優(yōu)先處理 @Configuration 類(lèi)。
- 組件類(lèi):掃描并注冊(cè)帶有 @Component 及其衍生注解的類(lèi)。
- 手動(dòng)注冊(cè)的 Bean:處理 @Bean 注解定義的 Bean。
2.5 Bean的依賴(lài)注入
構(gòu)造器注入:推薦的方式,適用于強(qiáng)制依賴(lài)。
@Service
public class MyService {
private final MyRepository repository;
@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
}Setter 注入:適用于可選依賴(lài)
@Service
public class MyService {
private MyRepository repository;
@Autowired
public void setRepository(MyRepository repository) {
this.repository = repository;
}
}字段注入:不推薦,因?yàn)椴焕跍y(cè)試和代碼可讀性。
@Service
public class MyService {
@Autowired
private MyRepository repository;
}到此這篇關(guān)于Springboot控制反轉(zhuǎn)與Bean對(duì)象的文章就介紹到這了,更多相關(guān)Springboot控制反轉(zhuǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot的控制反轉(zhuǎn)和自動(dòng)裝配示例代碼
- 淺析springboot通過(guò)面向接口編程對(duì)控制反轉(zhuǎn)IOC的理解
- SpringBoot bean的多種加載方式示例詳解
- SpringBoot測(cè)試類(lèi)注入Bean失敗的原因及分析
- SpringBoot中的Bean注入問(wèn)題
- springboot項(xiàng)目如何引用公共模塊的bean
- springboot加載注入bean的幾種方式
- Springboot加載所有Bean之后運(yùn)行方式
- 詳解SpringBoot如何讓指定的Bean先加載
- 在springboot中攔截器Filter中注入bean失敗問(wèn)題及解決
相關(guān)文章
mybatis 為什么千萬(wàn)不要使用 where 1=1
這篇文章主要介紹了mybatis 為什么千萬(wàn)不要使用 where 1=1,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
如何實(shí)現(xiàn)Java的ArrayList經(jīng)典實(shí)體類(lèi)
ArrayList是Java集合框架中一個(gè)經(jīng)典的實(shí)現(xiàn)類(lèi)。他比起常用的數(shù)組而言,明顯的優(yōu)點(diǎn)在于,可以隨意的添加和刪除元素而不需考慮數(shù)組的大小。下面跟著小編一起來(lái)看下吧2017-02-02
Java數(shù)據(jù)結(jié)構(gòu)之實(shí)現(xiàn)跳表
今天帶大家來(lái)學(xué)習(xí)Java數(shù)據(jù)結(jié)構(gòu)的相關(guān)知識(shí),文中對(duì)用Java實(shí)現(xiàn)跳表作了非常詳細(xì)的圖文解說(shuō)及代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05
Spring Cloud Stream與Kafka集成步驟(項(xiàng)目實(shí)踐)
Spring Cloud Stream是一個(gè)用于構(gòu)建消息驅(qū)動(dòng)微服務(wù)的框架,它是基于Spring Boot和Spring Integration創(chuàng)建的,旨在簡(jiǎn)化與消息中間件的集成工作,本教程介紹了如何結(jié)合Spring Cloud Stream框架和Apache Kafka消息代理,創(chuàng)建一個(gè)集成示例應(yīng)用,感興趣的朋友一起看看吧2025-08-08
java如何將控制臺(tái)輸出日志寫(xiě)入到指定文件中
這篇文章主要介紹了java如何將控制臺(tái)輸出日志寫(xiě)入到指定文件中問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之養(yǎng)老院管理系統(tǒng)的實(shí)現(xiàn)
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+JSP+Easyui+maven+mysql實(shí)現(xiàn)一個(gè)養(yǎng)老院管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2022-03-03

