Spring Core
容器(創(chuàng)建并管理bean的容器)
創(chuàng)建:使用反射技術(shù),創(chuàng)建bean的實(shí)例設(shè)計(jì):使用工廠模式(BeanFactory)管理:容器中的每個(gè)bean,Spring容器默認(rèn)按照單例方式管理,scope屬性為singleton,可以通過(guò)設(shè)置<bean scope="prototype"/>更改為每次獲取時(shí)創(chuàng)建不同的實(shí)例。
<!--業(yè)務(wù)層
Spring默認(rèn)使用單例的方式管理Bean;默認(rèn)狀態(tài)下,獲取Bean多次為同一個(gè)對(duì)象(hashcode相同)-->
<!-- <bean id="messageServiceImpl" class="com.chen.service.impl.MessageServiceImpl" /> -->
<!--默認(rèn)為單例模式:scope屬性為singleton-->
<!--<bean id="messageServiceImpl" class="com.chen.service.impl.MessageServiceImpl" scope="singleton"/>-->
<!--每次都是新實(shí)例scope屬性為prototype -->
<!--<bean id="messageServiceBean" class="com.apesource.service.impl.MessageSeriviceImpl"/>-->
?
ApplicationContext:?ClassPathXmlApplicationContext :在classpath路徑下加載xml配置文件,完成Spring容器的加載;或者, 采用注解方式時(shí),需要在xml配置 文件中使用<context:component-scan />完成類掃描。?AnnotationConfigApplicationContext :基于注解配置的Spring容器加載方式。
ApplicationContextcontext=newAnnotationConfigApplicationContext("com.apesource");
UserControlleruserController=(UserController)context.getBean("userController");
userController.execouteDosth();
?
ICO或者DI
?IOC:Inverse Of Control(控制翻轉(zhuǎn))?DI:Dependency Injection(依賴注入)??思想:將項(xiàng)目中的類(組件)交給Spring容器管理,按照組件之間彼此的以來(lái)關(guān)系(采用xml配置文件或者注解),完成組件之間的注入,降低組件之間的耦合??三種注入方式:①屬性注入②構(gòu)造注入(使用有參構(gòu)造方法進(jìn)行注入)③接口注入
<beanid="messageControllerBean"class="com.apesource.web.MessageController">
<!--將容器中的messageServiceBean,注入給當(dāng)前Controller的messageService屬性(通過(guò)該屬性的setter)-->
<!--<property name="messageService" ref="messageServiceBean"/>-->
<constructor-argname="messageService"ref="messageServiceBean"/>
<constructor-argname="message"value="哈哈哈哈"/>
</bean>
??三種配置方式:①XML:優(yōu)勢(shì)——配置內(nèi)容直觀清晰,擴(kuò)展靈活劣勢(shì)——配置繁瑣②注解:優(yōu)勢(shì)——簡(jiǎn)潔劣勢(shì)——擴(kuò)展不靈活③JavaConfig:優(yōu)勢(shì)——借助IDE工具,確保配置內(nèi)容準(zhǔn)確劣勢(shì)——配置代碼比較多,擴(kuò)展不靈活
注解
聲明bean
@Component:組件@Controller:控制器組件@Service:業(yè)務(wù)層組件@Repository:數(shù)據(jù)訪問(wèn)層組件
聲明注入
Spring Framework :?@Autowired :自動(dòng)裝配(默認(rèn)按照類型自動(dòng)裝配) ,按照當(dāng)前聲明的接口類型,在容器中查找該接口實(shí)現(xiàn)類對(duì)象bean ,進(jìn)行自動(dòng)注入(裝配)。?@Qualifier :按照bean名稱自動(dòng)裝配,與@Autowired注解配合使用。按照當(dāng)前指定的bean名稱,在容器中查找該名稱對(duì)應(yīng)的bean ,進(jìn)行自動(dòng)注入(裝配)。Java標(biāo)準(zhǔn)注解:?@Resource : javax擴(kuò)展包提供的注解,完成自動(dòng)注入 ,默認(rèn)按照類型自動(dòng)注入,也可以使用name屬'性進(jìn)行按名稱自動(dòng)注入
其他方式:
@primary:當(dāng)前bean為主要bean,當(dāng)發(fā)現(xiàn)多個(gè)相同類型的bean,以主要bean為首選@Scope("prototype") : 設(shè)置bean的作用域?yàn)槊看潍@取時(shí)創(chuàng)建新的bean;默認(rèn)為單例。@Configuration :設(shè)置當(dāng)前類為配置類。(JavaConfig配置中使用)@Bean :設(shè)置當(dāng)前方法為bean的創(chuàng)建方法,方法名即為bean的名稱。( JavaConfig配置中使用)