上文中我們簡單介紹了Spring和Spring Framework的元件,那麼這些Spring Framework元件是如何配合工作的呢?本文主要承接上文,向你展示Spring Framework元件的典型應用場景和基於這個場景設計出的簡單案例,並以此引出Spring的核心要點,比如IOC和AOP等;在此基礎上還引入了不同的設定方式, 如XML,Java設定和註解方式的差異。@pdai
上文中,我們展示了Spring和Spring Framework的元件, 這裡對於開發者來說有幾個問題:
- 首先,對於Spring進階,直接去看IOC和AOP,存在一個斷層,所以需要整體上構建對Spring框架認知上進一步深入,這樣才能構建知識體系。
- 其次,很多開發者入門都是從Spring Boot開始的,他對Spring整體框架底層,以及發展歷史不是很瞭解; 特別是對於一些老舊專案維護和底層bug分析沒有全域性觀。
- 再者,Spring代表的是一種框架設計理念,需要全域性上理解Spring Framework元件是如何配合工作的,需要理解它設計的初衷和未來趨勢。
如下是官方在解釋Spring框架的常用場景的圖
我加上一些註釋後,是比較好理解的;引入這個圖,重要的原因是為後面設計一個案例幫助你構建認知。
結合上面的使用場景,設計一個查詢使用者的案例的兩個需求,來看Spring框架幫我們簡化了什麼開發工作:
- 查詢使用者資料 - 來看DAO+POJO-> Service 的初始化和裝載。
- 給所有Service的查詢方法記錄紀錄檔
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tech.pdai</groupId>
<artifactId>001-spring-framework-demo-helloworld-xml</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring.version>5.3.9</spring.version>
<aspectjweaver.version>1.9.6</aspectjweaver.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
</dependencies>
</project>
package tech.pdai.springframework.entity;
/**
* @author pdai
*/
public class User {
/**
* user's name.
*/
private String name;
/**
* user's age.
*/
private int age;
/**
* init.
*
* @param name name
* @param age age
*/
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package tech.pdai.springframework.dao;
import java.util.Collections;
import java.util.List;
import tech.pdai.springframework.entity.User;
/**
* @author pdai
*/
public class UserDaoImpl {
/**
* init.
*/
public UserDaoImpl() {
}
/**
* mocked to find user list.
*
* @return user list
*/
public List<User> findUserList() {
return Collections.singletonList(new User("pdai", 18));
}
}
並增加daos.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="tech.pdai.springframework.dao.UserDaoImpl">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
package tech.pdai.springframework.service;
import java.util.List;
import tech.pdai.springframework.dao.UserDaoImpl;
import tech.pdai.springframework.entity.User;
/**
* @author pdai
*/
public class UserServiceImpl {
/**
* user dao impl.
*/
private UserDaoImpl userDao;
/**
* init.
*/
public UserServiceImpl() {
}
/**
* find user list.
*
* @return user list
*/
public List<User> findUserList() {
return this.userDao.findUserList();
}
/**
* set dao.
*
* @param userDao user dao
*/
public void setUserDao(UserDaoImpl userDao) {
this.userDao = userDao;
}
}
並增加services.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="userService" class="tech.pdai.springframework.service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
package tech.pdai.springframework.aspect;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author pdai
*/
@Aspect
public class LogAspect {
/**
* aspect for every methods under service package.
*/
@Around("execution(* tech.pdai.springframework.service.*.*(..))")
public Object businessService(ProceedingJoinPoint pjp) throws Throwable {
// get attribute through annotation
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
System.out.println("execute method: " + method.getName());
// continue to process
return pjp.proceed();
}
}
並增加aspects.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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<context:component-scan base-package="tech.pdai.springframework" />
<aop:aspectj-autoproxy/>
<bean id="logAspect" class="tech.pdai.springframework.aspect.LogAspect">
<!-- configure properties of aspect here as normal -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
package tech.pdai.springframework;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import tech.pdai.springframework.entity.User;
import tech.pdai.springframework.service.UserServiceImpl;
/**
* @author pdai
*/
public class App {
/**
* main interfaces.
*
* @param args args
*/
public static void main(String[] args) {
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("aspects.xml", "daos.xml", "services.xml");
// retrieve configured instance
UserServiceImpl service = context.getBean("userService", UserServiceImpl.class);
// use configured instance
List<User> userList = service.findUserList();
// print info from beans
userList.forEach(a -> System.out.println(a.getName() + "," + a.getAge()));
}
}
那麼Spring框架幫助我們做什麼,它體現了什麼哪些要點呢?
來看第一個需求:查詢使用者(service通過呼叫dao查詢pojo),本質上如何建立User/Dao/Service等;
UserDaoImpl userDao = new UserDaoImpl();
UserSericeImpl userService = new UserServiceImpl();
userService.setUserDao(userDao);
List<User> userList = userService.findUserList();
Bean的建立和使用分離了。
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("aspects.xml", "daos.xml", "services.xml");
// retrieve configured instance
UserServiceImpl service = context.getBean("userService", UserServiceImpl.class);
// use configured instance
List<User> userList = service.findUserList();
更進一步,你便能理解為何會有如下的知識點了:
這邊引入我們後續的相關文章:Spring基礎 - Spring之控制反轉(IOC)
來看第二個需求:給Service所有方法呼叫新增紀錄檔(呼叫方法時),本質上是解耦問題;
/**
* find user list.
*
* @return user list
*/
public List<User> findUserList() {
System.out.println("execute method findUserList");
return this.userDao.findUserList();
}
/**
* aspect for every methods under service package.
*/
@Around("execution(* tech.pdai.springframework.service.*.*(..))")
public Object businessService(ProceedingJoinPoint pjp) throws Throwable {
// get attribute through annotation
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
System.out.println("execute method: " + method.getName());
// continue to process
return pjp.proceed();
}
更進一步,你便能理解為何會有如下的知識點了:
這邊引入我們後續的相關文章:Spring基礎 - Spring之面向切面程式設計(AOP)
通過上述的框架介紹和例子,已經初步知道了Spring設計的兩個大的要點:IOC和AOP;從框架的設計角度而言,更為重要的是簡化開發,比如提供更為便捷的設定Bean的方式,直至0設定(即約定大於設定)。這裡我將通過Spring歷史版本的發展,和SpringBoot的推出等,來幫你理解Spring框架是如何逐步簡化開發的。
在前文的例子中, 通過xml設定方式實現的,這種方式實際上比較麻煩; 我通過Java設定進行改造:
package tech.pdai.springframework.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import tech.pdai.springframework.aspect.LogAspect;
import tech.pdai.springframework.dao.UserDaoImpl;
import tech.pdai.springframework.service.UserServiceImpl;
/**
* @author pdai
*/
@EnableAspectJAutoProxy
@Configuration
public class BeansConfig {
/**
* @return user dao
*/
@Bean("userDao")
public UserDaoImpl userDao() {
return new UserDaoImpl();
}
/**
* @return user service
*/
@Bean("userService")
public UserServiceImpl userService() {
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(userDao());
return userService;
}
/**
* @return log aspect
*/
@Bean("logAspect")
public LogAspect logAspect() {
return new LogAspect();
}
}
package tech.pdai.springframework;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tech.pdai.springframework.config.BeansConfig;
import tech.pdai.springframework.entity.User;
import tech.pdai.springframework.service.UserServiceImpl;
/**
* @author pdai
*/
public class App {
/**
* main interfaces.
*
* @param args args
*/
public static void main(String[] args) {
// create and configure beans
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfig.class);
// retrieve configured instance
UserServiceImpl service = context.getBean("userService", UserServiceImpl.class);
// use configured instance
List<User> userList = service.findUserList();
// print info from beans
userList.forEach(a -> System.out.println(a.getName() + "," + a.getAge()));
}
}
更進一步,Java 5開始提供註解支援,Spring 2.5 開始完全支援基於註解的設定並且也支援JSR250 註解。在Spring後續的版本發展傾向於通過註解和Java設定結合使用.
package tech.pdai.springframework.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author pdai
*/
@Configuration
@EnableAspectJAutoProxy
public class BeansConfig {
}
/**
* @author pdai
*/
@Repository
public class UserDaoImpl {
/**
* mocked to find user list.
*
* @return user list
*/
public List<User> findUserList() {
return Collections.singletonList(new User("pdai", 18));
}
}
/**
* @author pdai
*/
@Service
public class UserServiceImpl {
/**
* user dao impl.
*/
@Autowired
private UserDaoImpl userDao;
/**
* find user list.
*
* @return user list
*/
public List<User> findUserList() {
return userDao.findUserList();
}
}
package tech.pdai.springframework;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tech.pdai.springframework.entity.User;
import tech.pdai.springframework.service.UserServiceImpl;
/**
* @author pdai
*/
public class App {
/**
* main interfaces.
*
* @param args args
*/
public static void main(String[] args) {
// create and configure beans
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
"tech.pdai.springframework");
// retrieve configured instance
UserServiceImpl service = context.getBean(UserServiceImpl.class);
// use configured instance
List<User> userList = service.findUserList();
// print info from beans
userList.forEach(a -> System.out.println(a.getName() + "," + a.getAge()));
}
}
Springboot實際上通過約定大於設定的方式,使用xx-starter統一的對Bean進行預設初始化,使用者只需要很少的設定就可以進行開發了。
這個因為很多開發者都是從SpringBoot開始著手開發的,所以這個比較好理解。我們需要的是將知識點都串聯起來,構築認知體系。
最後結合Spring歷史版本總結下它的發展:
(這樣是不是能夠幫助你在整體上構建了知識體系的認知了呢?)
PS:相關程式碼,可以通過這裡直接檢視
首先, 從Spring框架的整體架構和組成對整體框架有個認知。
其次,通過案例引出Spring的核心(IoC和AOP),同時對IoC和AOP進行案例使用分析。
基於Spring框架和IOC,AOP的基礎,為構建上層web應用,需要進一步學習SpringMVC。
Spring進階 - IoC,AOP以及SpringMVC的原始碼分析
ConcurrentHashMap<String, Object>
;並且BeanDefinition介面中包含了這個類的Class資訊以及是否是單例等。那麼如何從BeanDefinition中範例化Bean物件呢,這是本文主要研究的內容?