一:Spring框架功能整體介紹
1: Spring Core Container:
模塊作用:Core 和 Beans 模塊是框架的基礎部分,提供 IoC (轉控制)和依賴注入特性。 這里的基礎概念是 BeanFactory,它提供對 Factory 模式的經典實 現來消除對程序單例模式依賴,并真正地允許你從程序邏輯中分離出依賴關系和配置
1.1) Core
主要包含 Spring 框架基本的核心工具類, Spring 的其他組件都要用到這個包 里的類, Core模塊是其他組件的基 本核心。
1.2)Beans (BeanFacotry的作用)
它包含訪問配直文件、創建和管理 bean 以及進行 Inversion of Control I Dependency Injection ( IoC/DI )操作相關的所有類
1.3) Context(處理BeanFactory)
模構建于 Core 和 Beans 模塊基礎之上,提供了一種類似JNDI 注冊器的框架式的對象訪問方法。 Context 模塊繼承了 Beans 的特性,為 Spring 核心提供了大量擴展,添加了對國際化(例如資源綁定)、事件傳播、資源加載和對 Context 的透明創建的支持。 Context 模塊同時也支持 J2EE 的一些特 性, ApplicationContext 接口是 Context 模塊的關鍵本質區別:(使用BeanFacotry的bean是延時加載的,ApplicationContext是非延時加載的)
1.4)Expression Language
模塊提供了強大的表達式語言,用于在運行時查詢和操縱對象。 它是 JSP 2.1 規范中定義的unifed expression language 的擴展。 該語言支持設直/獲取屬 性的值,屬性的分配,方法的調用,訪問數組上下文( accessiong the context of arrays )、 容器和索引器、邏輯和算術運算符、命名變量以及從Spring的 IoC 容器中根據名稱檢 索對象。 它也支持 list 投影、選擇和一般的 list 聚合
2: Spring Data Access/Integration
2.1)JDBC
JDBC模塊提供了一個 JDBC 抽象層,它可以消除冗長的 JDBC 編碼和解析數據庫廠商特有的錯誤代碼。這個模塊包含了 Spring 對JDBC 數據訪問進行封裝的所有類
2.2)ORM
ORM模塊為流行的對象-關系映射 API,如 JPA、JDO、 Hibernate、 iBatis 等,提供了 一個交互層。 利用 ORM 封裝包,可以混合使用所有 Spring 提供的特性進行 O/R 映射, 如前邊提到的簡單聲 明性事務管理。
2.3)OXM
OXM 模塊提供了一個對 ObjecνXML 映射實現的抽象層,Object/XML 映射實現包括 JAXB、 Castor、 XMLBeans、 JiBX 和 XStrearn
2.4)JMS ( Java Messaging Service )
模塊主要包含了 一些制造和消 費消息的特性。
2.5) Transaction
支持編程和聲明性的事務管理,這些事務類必須實現特定的接口,并 且對所有的 POJO 都適用
3: Spring Web
Web 模塊:提供了基礎的面向 Web 的集成特性。例如,多文件上傳、使用 servlet listeners 初始化 IoC 容器以及一個面向 Web 的應用上下文。 它還包含 Spring 遠程支持中 Web 的相關部分。
4: Spring Aop
4.1)Aspects
模塊提供了對 AspectJ 的集成支持。
4.2)Instrumentation 模塊提供了 class instrumentation 支持和 classloader 實現,使得可以在特
定的應用服務器上使用
5:Test
Test 模塊支持使用 JUnit 和 TestNG 對 Spring 組件進行測試
6:Spring 容器繼承圖:
7:控制反轉和依賴注入
1、IOC容器的最最最最核心思想
ioc的思想最核心的地方在于,資源不由使用資源的雙方管理,而由不使用資源的第三方管理,這可以帶來很多好處。
第一,資源集中管理,實現資源的可配置和易管理。
第二,降低了使用資源雙方的依賴程度,也就是我們說的耦合度
二:Spring IOC 容器底層注解使用
2.1)xml配置文件的形式 VS 配置類的形式
①:基于xml的形式定義Bean的信息
<?xml version="1.0" encoding="UTF-8"?>
<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-/定義一個Bean的信息
<bean id="car" class="com.compent.Car"></bean>
</beans>
去容器中讀取Bean
public static void main( String[] args )
{
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
System.out.println(ctx.getBean("person"));
}
②:基于讀取配置類的形式定義Bean信息
@Configuration
public class MainConfig {
@Bean
public Person person(){
return new Person();
}
}
通過@Bean的形式是使用的話, bean的默認名稱是方法名,若@Bean(value="bean的名稱")那么bean的名稱是指定的
去容器中讀取Bean的信息(傳入配置類)
public static void main( String[] args )
{
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println(ctx.getBean("person"));
}
2.2)在配置類上寫@CompentScan注解來進行包掃描
@Configuration
@ComponentScan(basePackages = {"com.testcompentscan"})
public class MainConfig {
}
①:排除用法 excludeFilters(排除@Controller注解的,和TulingService的)
@Configuration
@ComponentScan(basePackages = {"com.testcompentscan"},excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {TService.class})
})
public class MainConfig {
}
②:包含用法 includeFilters ,注意,若使用包含的用法,需要把useDefaultFilters屬性設置為false(true表示掃描全部的)
@Configuration
@ComponentScan(basePackages = {"com.testcompentscan"},includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
},useDefaultFilters = false)
public class MainConfig {
}
③ @ComponentScan.Filter type的類型
a)注解形式的FilterType.ANNOTATION @Controller @Service @Repository @Compent
b)指定類型的 FilterType.ASSIGNABLE_TYPE @ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE,value = {TService.class})
c)aspectj類型的 FilterType.ASPECTJ(不常用)
d)正則表達式的 FilterType.REGEX(不常用)
e)自定義的 FilterType.CUSTOM
public enum FilterType {
//注解形式 比如@Controller @Service @Repository @Compent
ANNOTATION,
//指定的類型
ASSIGNABLE_TYPE,
//aspectJ形式的
ASPECTJ,
//正則表達式的
REGEX,
//自定義的
CUSTOM
}
③.①FilterType.CUSTOM 自定義類型如何使用
public class TulingFilterType implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//獲取當前類的注解源信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//獲取當前類的class的源信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//獲取當前類的資源信息
Resource resource = metadataReader.getResource();
if(classMetadata.getClassName().contains("dao")) {
return true;
}
return false;
}
}
@ComponentScan(basePackages = {"com.tuling.testcompentscan"},includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,value = TulingFilterType.class)
},useDefaultFilters = false)
public class MainConfig {
}
2.3)配置Bean的作用域對象
①:在不指定@Scope的情況下,所有的bean都是單實例的bean,而且是餓漢加載(容器啟動實例就創建好了)
@Bean
public Person person() {
return new Person();
}
②:指定@Scope為 prototype 表示為多實例的,而且還是懶漢模式加載(IOC容器啟動的時候,并不會創建對象,而是
在第一次使用的時候才會創建)
@Bean
@Scope(value = "prototype")
public Person person() {
return new Person();
}
③:@Scope指定的作用域方法取值
a) singleton 單實例的(默認)
b) prototype 多實例的
c) request 同一次請求
d) session 同一個會話級別
2.4)Bean的懶加載@Lazy
主要針對單實例的bean 容器啟動的時候,不創建對象,在第一次使用的時候才會創建該對象
@Bean
@Lazy
public Person person() {
return new Person();
}
2.5)@Conditional進行條件判斷等.
場景,有二個組件TAspect 和TLog ,我的TLog組件是依賴于TAspect的組件
應用:自己創建一個TCondition的類 實現Condition接口
public class TCondition implements Condition {
/**
*
* @param context
* @param metadata
* @return
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判斷容器中是否有tAspect的組件
if(context.getBeanFactory().containsBean("tAspect")) {
return true;
}
return false;
}
}
public class MainConfig {
@Bean
public TulingAspect tAspect() {
return new TAspect();
}
//當切 容器中有tAspect的組件,那么tLog才會被實例化.
@Bean
@Conditional(value = TCondition.class)
public TLog tLog() {
return new TLog();
}
}
2.6)往IOC 容器中添加組件的方式
①:通過@CompentScan +@Controller @Service @Respository @compent
適用場景: 針對我們自己寫的組件可以通過該方式來進行加載到容器中。
②:通過@Bean的方式來導入組件(適用于導入第三方組件的類)
③:通過@Import來導入組件 (導入組件的id為全類名路徑)
@Configuration
@Import(value = {Person.class, Car.class})
public class MainConfig {
}
通過@Import 的ImportSeletor類實現組件的導入 (導入組件的id為全類名路徑)
public class TImportSelector implements ImportSelector {
//可以獲取導入類的注解信息
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.testimport.compent.Dog"};
}
}
@Configuration
@Import(value = {Person.class, Car.class, TImportSelector.class})
public class MainConfig {
}
通過@Import的 ImportBeanDefinitionRegister導入組件 (可以指定bean的名稱)
public class TBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//創建一個bean定義對象
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Cat.class);
//把bean定義對象導入到容器中
registry.registerBeanDefinition("cat",rootBeanDefinition);
}
}
@Configuration
//@Import(value = {Person.class, Car.class})
//@Import(value = {Person.class, Car.class, TImportSelector.class})
@Import(value = {Person.class, Car.class, TImportSelector.class, TBeanDefinitionRegister.class})
public class MainConfig {
}
④:通過實現FacotryBean接口來實現注冊 組件
public class CarFactoryBean implements FactoryBean<Car> {
/返回bean的對象
@Override
public Car getObject() throws Exception {
return new Car();
}
/返回bean的類型
@Override
public Class<?> getObjectType() {
return Car.class;
}
/是否為單利
@Override
public boolean isSingleton() {
return true;
2.7)Bean的初始化方法和銷毀方法.
①:什么是bean的生命周期?
bean的創建----->初始化----->銷毀方法
由容器管理Bean的生命周期,我們可以通過自己指定bean的初始化方法和bean的銷毀方法
@Configuration
public class MainConfig {
//指定了bean的生命周期的初始化方法和銷毀方法.
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
針對單實例bean的話,容器啟動的時候,bean的對象就創建了,而且容器銷毀的時候,也會調用Bean的銷毀方法
針對多實例bean的話,容器啟動的時候,bean是不會被創建的而是在獲取bean的時候被創建,而且bean的銷毀不受IOC容器的管理.
②:通過 InitializingBean和DisposableBean 的兩個接口實現bean的初始化以及銷毀方法
@Component
public class Person implements InitializingBean,DisposableBean {
public Person() {
System.out.println("Person的構造方法");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean的destroy()方法 ");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean的 afterPropertiesSet方法");
}
}
③:通過JSR250規范 提供的注解@PostConstruct 和@ProDestory標注的方法
@Component
public class Book {
public Book() {
System.out.println("book 的構造方法");
}
@PostConstruct
public void init() {
System.out.println("book 的PostConstruct標志的方法");
}
@PreDestroy
public void destory() {
System.out.println("book 的PreDestory標注的方法");
}
}
④:通過Spring的BeanPostProcessor的 bean的后置處理器會攔截所有bean創建過程
postProcessBeforeInitialization 在init方法之前調用
postProcessAfterInitialization 在init方法之后調用
@Component
public class TBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("TBeanPostProcessor...postProcessBeforeInitialization:"+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("TulingBeanPostProcessor...postProcessAfterInitialization:"+beanName);
return bean;
}
}
???===
BeanPostProcessor的執行時機
populateBean(beanName, mbd, instanceWrapper)
initializeBean{
applyBeanPostProcessorsBeforeInitialization()
invokeInitMethods{
isInitializingBean.afterPropertiesSet
自定義的init方法
}
applyBeanPostProcessorsAfterInitialization()方法
}
2.8)bean賦值
通過@Value + @PropertySource來給組件賦值
public class Person {
//通過普通的方式
@Value("司馬")
private String firstName;
//spel方式來賦值
@Value("#{28-8}")
private Integer age;
通過讀取外部配置文件的值
@Value("${person.lastName}")
private String lastName;
}
@Configuration
@PropertySource(value = {"classpath:person.properties"}) //指定外部文件的位置
public class MainConfig {
@Bean
public Person person() {
return new Person();
}
}
2.9)自動裝配
@AutoWired的使用
自動注入:
//一個Dao
@Repository
public class TulingDao {
}
@Service
public class TulingService {
@Autowired
private TulingDao tulingDao;
}
結論:
a:自動裝配首先時按照類型進行裝配,若在IOC容器中發現了多個相同類型的組件,那么就按照屬性名稱來進行裝配
@Autowired
private TDao tDao;
比如,我容器中有兩個TDao類型的組件 一個叫tDao 一個叫tDao2
那么我們通過@AutoWired 來修飾的屬性名稱時tDao,那么拿就加載容器的tDao組件,若屬性名稱為
tDao2 那么他就加載的時tDao2組件
b:假設我們需要指定特定的組件來進行裝配,我們可以通過使用@Qualifier("tDao")來指定裝配的組件
或者在配置類上的@Bean加上@Primary注解
@Autowired
@Qualifier("tDao")
private TDao tDao2;
c:假設我們容器中即沒有tDao 和tDao2,那么在裝配的時候就會拋出異常
No qualifying bean of type 'com.tuling.testautowired.TulingDao' available
若我們想不拋異常 ,我們需要指定 required為false的時候可以了
@Autowired(required = false)
@Qualifier("tDao")
private TDao tulingDao2;
d:@Resource(JSR250規范)
功能和@AutoWired的功能差不多一樣,但是不支持@Primary 和@Qualifier的支持
e:@InJect(JSR330規范)
需要導入jar包依賴
功能和支持@Primary功能 ,但是沒有Require=false的功能
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
f:使用autowired 可以標注在方法上
標注在set方法上
//@Autowired
public void setTLog(TLog tLog) {
this.tLog = tLog;
}
標注在構造方法上
@Autowired
public TulingAspect(TLog tLog) {
this.tLog = tLog;
}
標注在配置類上的入參中(可以不寫)
@Bean
public TAspect tAspect(@Autowired TLog tLog) {
TAspect tAspect = new TAspect(tLog);
return tAspect;
}
3.0) 我們自己的組件 需要使用spring ioc的底層組件的時候,比如 ApplicationContext等
我們可以通過實現XXXAware接口來實現
@Component
public class TCompent implements ApplicationContextAware,BeanNameAware {
private ApplicationContext applicationContext;
@Override
public void setBeanName(String name) {
System.out.println("current bean name is :【"+name+"】");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
3.1)通過@Profile注解 來根據環境來激活標識不同的Bean
@Profile標識在類上,那么只有當前環境匹配,整個配置類才會生效
@Profile標識在Bean上 ,那么只有當前環境的Bean才會被激活
沒有標志為@Profile的bean 不管在什么環境都可以被激活
@Configuration
@PropertySource(value = {"classpath:ds.properties"})
public class MainConfig implements EmbeddedValueResolverAware {
@Value("${ds.username}")
private String userName;
@Value("${ds.password}")
private String password;
private String jdbcUrl;
private String classDriver;
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
}
//標識為測試環境才會被裝配
@Bean
@Profile(value = "test")
public DataSource testDs() {
return buliderDataSource(new DruidDataSource());
}
//標識開發環境才會被激活
@Bean
@Profile(value = "dev")
public DataSource devDs() {
return buliderDataSource(new DruidDataSource());
}
//標識生產環境才會被激活
@Bean
@Profile(value = "prod")
public DataSource prodDs() {
return buliderDataSource(new DruidDataSource());
}
private DataSource buliderDataSource(DruidDataSource dataSource) {
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setDriverClassName(classDriver);
dataSource.setUrl(jdbcUrl);
return dataSource;
}
激活切換環境的方法
方法一:通過運行時jvm參數來切換 -Dspring.profiles.active=test|dev|prod
方法二:通過代碼的方式來激活
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("test","dev");
ctx.register(MainConfig.class);
ctx.refresh();
printBeanName(ctx);
}