1 spring框架概述
1.1 什么是spring
- spring是一個(gè)輕量級(jí)(依賴資源少、銷毀的資源少)的開源框架,spring的核心是控制反轉(zhuǎn)(IoC)和面向切面(AOP)
- spring是一個(gè)分層的JavaSE/EE full-stack(一站式)輕量級(jí)開源框架
- web層:struts,spring MVC
- service層:spring
- dao層:hibernate,mybatis,jdbcTemplate,spring dateaa
1.2 spring的優(yōu)點(diǎn)
- 方便解耦,簡(jiǎn)化開發(fā)(高內(nèi)聚低耦合)
- spring就是一個(gè)大工廠(容器),可以將所有對(duì)象創(chuàng)建和依賴關(guān)系維護(hù),交給Spring管理
- spring工廠是用于生成bean
- AOP編程的支持
- spring提供面向切面編程,可以方便的實(shí)現(xiàn)對(duì)程序進(jìn)行權(quán)限攔截、運(yùn)行監(jiān)控等功能
- 聲明式事務(wù)的支持
- 只需要通過(guò)配置就可以完成對(duì)事務(wù)的管理,而無(wú)需手動(dòng)編程
- 方便程序的測(cè)試
- spring對(duì)Junit4支持,可以通過(guò)注解方便的測(cè)試spring程序
- 方便集成各種優(yōu)秀框架
- spring不排斥各種優(yōu)秀的開源框架,其內(nèi)部提供了對(duì)各種優(yōu)秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持
- 低JavaEE API的使用難度
- spring 對(duì)JavaEE開發(fā)中非常難用的一些API(JDBC、JavaMail、遠(yuǎn)程調(diào)用等),都提供了封裝,使這些API應(yīng)用難度大大降低
1.3 spring體系結(jié)構(gòu)

spring體系結(jié)構(gòu)
- spring核心容器:beans、core、context、expression
2 IoC案例
2.1 IoC概述
- IoC意為:控制反轉(zhuǎn)(Inverse of Control)
- 之前開發(fā)中,直接new一個(gè)對(duì)象即可。現(xiàn)在將此步驟翻轉(zhuǎn)給spring,由spring創(chuàng)建對(duì)象實(shí)例
- 需要實(shí)例對(duì)象時(shí),從spring工廠(容器)中獲得,需要將實(shí)現(xiàn)類的全限定名稱配置到xml文件中
2.2 所需jar包
- 4個(gè)核心包(beans、core、context、expression)
-
1個(gè)依賴包(commons-loggins...jar)
jar包
2.3 創(chuàng)建目標(biāo)類
- 提供UserService接口和實(shí)現(xiàn)類
- 獲得UserService實(shí)現(xiàn)類的實(shí)例
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("a_ico add user");
}
}
2.4 xml配置文件
- 位置:任意,開發(fā)中一般在classpath下(src)
- 名稱:任意,開發(fā)中常用
applicationContext.xml - 內(nèi)容:添加schema約束
- 約束文件位置:
spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\ xsd-config.html
<?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">
<!-- 配置service
<bean> 配置需要?jiǎng)?chuàng)建的對(duì)象
id:用于之后從spring容器獲得實(shí)例時(shí)使用的
class:需要?jiǎng)?chuàng)建實(shí)例的全限定類名 -->
<bean id="userServiceId" class="com.itheima.a_ioc.UserServiceImpl"></bean>
</beans>
2.5 測(cè)試
@Test
public void demo02(){
//從spring容器獲得
//1 獲得容器
String xmlPath = "com/itheima/a_ioc/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//2 獲得內(nèi)容,不需要自己new,都是從spring容器獲得
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
}
3 DI案例
3.1 DI概述
- DI:Dependency Injection,依賴注入
- 依賴:一個(gè)對(duì)象需要使用另一個(gè)對(duì)象
- 注入:通過(guò)setter方法進(jìn)行另一個(gè)對(duì)象實(shí)例設(shè)置
3.2 創(chuàng)建dao接口和dao實(shí)現(xiàn)類
public interface BookDao {
public void addBook();
}
public class BookDaoImpl implements BookDao {
@Override
public void addBook() {
System.out.println("di");
}
}
3.3 創(chuàng)建bookService接口和bookService實(shí)現(xiàn)類
public interface BookService {
public void addBook();
}
public class BookServiceImpl implements BookService {
// 方式1:之前,接口=實(shí)現(xiàn)類
//private BookDao bookDao = new BookDaoImpl();
// 方式2:接口 + setter
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook() {
this.bookDao.addBook();
}
}
3.4 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">
<!--
模擬spring執(zhí)行過(guò)程
創(chuàng)建service實(shí)例:BookService bookService = new BookServiceImpl() IoC <bean>
創(chuàng)建dao實(shí)例:BookDao bookDao = new BookDaoImpl() IoC
將dao設(shè)置給service:bookService.setBookDao(bookDao); DI <property>
<property> 用于進(jìn)行屬性注入
name: bean的屬性名,通過(guò)setter方法獲得
setBookDao ##> BookDao ##> bookDao
ref :另一個(gè)bean的id值的引用
-->
<!-- 創(chuàng)建service -->
<bean id="bookServiceImplId" class="b_di.BookServiceImpl">
<property name="bookDao" ref="bookDaoImplId"></property>
</bean>
<!-- 創(chuàng)建dao實(shí)例 -->
<bean id="bookDaoImplId" class="b_di.BookDaoImpl"></bean>
</beans>
3.5 測(cè)試
public class Test {
@org.junit.Test
public void test01(){
String xmlPath="b_di/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
BookService bookService=applicationContext.getBean("bookServiceImplId",BookService.class);
bookService.addBook();
}
}
4 核心API
-
API結(jié)構(gòu)圖
核心API - BeanFactory:這是一個(gè)工廠,用于生成任意bean,采取延遲加載,第一次getBean時(shí)才會(huì)初始化Bean
- ApplicationContext:是BeanFactory的子接口,功能更強(qiáng)大。(國(guó)際化處理、事件傳遞、Bean自動(dòng)裝配、各種不同應(yīng)用層的Context實(shí)現(xiàn))。當(dāng)配置文件被加載,就進(jìn)行對(duì)象實(shí)例化
- ClassPathXmlApplicationContext用于加載classpath(類路徑、src)下的xml,加載xml運(yùn)行時(shí)位置 -->/WEB-INF/classes/...xml
- FileSystemXmlApplicationContext用于加載指定盤符下的xml,加載xml運(yùn)行時(shí)位置 --> /WEB-INF/...xml,通過(guò)java web ServletContext.getRealPath() 獲得具體盤符
@Test
public void demo02(){
//使用BeanFactory --第一次條用getBean實(shí)例化
String xmlPath = "com/itheima/b_di/beans.xml";
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
bookService.addBook();
}
5 bean的實(shí)例化方式
5.1 默認(rèn)構(gòu)造
5.2 靜態(tài)工廠
- 創(chuàng)建接口
public interface UserService {
public void addUser();
}
- 創(chuàng)建實(shí)現(xiàn)類
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("靜態(tài)工廠");
}
}
- 創(chuàng)建工廠
public class MyBeanFactory {
public static UserService createService(){
return new UserServiceImpl();
}
}
- 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">
<!-- 將靜態(tài)工廠創(chuàng)建的實(shí)例交予spring
class 確定靜態(tài)工廠全限定類名
factory-method 確定靜態(tài)方法名
-->
<bean id="userServiceImplId" class="c_static.MyBeanFactory" factory-method="createService"></bean>
</beans>
- 測(cè)試
@org.junit.Test
public void test01(){
String xmlPath="c_static/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
userService.addUser();
}
5.3 實(shí)例工廠
- 必須先有工廠實(shí)例對(duì)象,通過(guò)實(shí)例對(duì)象創(chuàng)建對(duì)象,提供所有的方法都是“非靜態(tài)”的
- 創(chuàng)建接口
public interface UserService {
public void addUser();
}
- 創(chuàng)建實(shí)現(xiàn)類
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("實(shí)例工廠");
}
}
- 創(chuàng)建工廠
public class MyBeanFactory {
public UserService createService(){
return new UserServiceImpl();
}
}
- 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">
<!-- 創(chuàng)建工廠實(shí)例 -->
<bean id="myBeanFactorlId" class="d_factory.MyBeanFactory"></bean>
<!-- factory-bean:確定工廠實(shí)例
factory-method:確定普通方法 -->
<bean id="userServiceImplId" factory-bean="myBeanFactorlId" factory-method="createService"></bean>
</beans>
- 測(cè)試
public class Test {
@org.junit.Test
public void test01(){
String xmlPath="d_factory/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
userService.addUser();
}
}
6 Bean的種類
- 普通bean:之前操作的都是普通bean,
<bean id="" class="A">,spring直接創(chuàng)建A實(shí)例,并返回 - FactoryBean:是一個(gè)特殊的bean,具有工廠生成對(duì)象能力,只能生成特定的對(duì)象。bean必須使用FactoryBean接口,此接口提供方法
getObject()用于獲得特定bean。<bean id="" class="FB">先創(chuàng)建FB實(shí)例,使用調(diào)用getObject()方法,并返回方法的返回值
FB fb = new FB();
return fb.getObject();
- BeanFactory 和 FactoryBean 對(duì)比
- BeanFactory:工廠,用于生成任意bean
- 特殊bean,用于生成另一個(gè)特定的bean。例如:
ProxyFactoryBean,此工廠bean用于生產(chǎn)代理。<bean id="" class="....ProxyFactoryBean">獲得代理對(duì)象實(shí)例,AOP使用
7 作用域
- 作用域:用于確定創(chuàng)建bean實(shí)例的個(gè)數(shù)
| 類別 | 說(shuō)明 |
|---|---|
| singleton | 在spring ioc容器中僅存在一個(gè)Bean實(shí)例,Bean以單例方式存在,默認(rèn)值 |
| prototype | 每次從容器中調(diào)用Bean時(shí),都返回一個(gè)新的實(shí)例,即每次都調(diào)用getBean()時(shí),相當(dāng)于執(zhí)行new XxxBean() |
| request | 每次HTTP請(qǐng)求都會(huì)創(chuàng)建一個(gè)新的Bean,該作用域僅適用于WebApplicationContext環(huán)境 |
| session | 同一個(gè)HTTP Session共享一個(gè)Bean,不同Session使用不同Bean,僅適用于WebApplicationContext環(huán)境 |
| globalSession | 一般用戶Portlet應(yīng)用環(huán)境,該作用域僅適用于WebApplicationContext環(huán)境 |
- 取值
- singleton:?jiǎn)卫?,默認(rèn)值
- prototype:多例,每執(zhí)行一次getBean將獲得一個(gè)實(shí)例。例如:struts整合spring,配置action多例
- 配置信息
<bean id="userServiceId" class="com.itheima.d_scope.UserServiceImpl"
scope="prototype" ></bean>
8 生命周期
- 目標(biāo)方法執(zhí)行前后執(zhí)行后,將進(jìn)行初始化或銷毀
<bean id="" class="" init-method="初始化方法名稱" destroy-method="銷毀的方法名稱">
- 創(chuàng)建接口
public interface UserService {
public void addUser();
}
- 創(chuàng)建實(shí)現(xiàn)類
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("lifecycle...");
}
public void myInit(){
System.out.println("初始化");
}
public void myDestory(){
System.out.println("銷毀");
}
}
- 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">
<!-- init-method 用于配置初始化方法,準(zhǔn)備數(shù)據(jù)等
destroy-method 用于配置銷毀方法,清理資源等 -->
<bean id="userServiceImplId" class="f_lifecycle.UserServiceImpl" init-method="myInit" destroy-method="myDestory"></bean>
</beans>
- 測(cè)試
/**
* 1. 容器必須close,銷毀方法才執(zhí)行
* 2. 必須是單例的
*/
public class Test {
@org.junit.Test
public void test01() throws Exception{
String xmlPath="f_lifecycle/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
userService.addUser();
//使用反射調(diào)用close方法
applicationContext.getClass().getMethod("close").invoke(applicationContext);
}
@org.junit.Test
public void test02(){
String xmlPath="f_lifecycle/applicationContext.xml";
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
userService.addUser();
//使用ClassPathXmlApplicationContext調(diào)用close
applicationContext.close();
}
}
9 后處理Bean:BeanPostProcessor
- spring 提供一種機(jī)制,只要實(shí)現(xiàn)此接口
BeanPostProcessor,并將實(shí)現(xiàn)類提供給spring容器,spring容器將自動(dòng)執(zhí)行,在初始化方法前執(zhí)行before(),在初始化方法后執(zhí)行after(),spring提供工廠勾子,用于修改實(shí)例對(duì)象,可以生成代理對(duì)象,是AOP底層 - 創(chuàng)建接口
public interface UserService {
public void addUser();
}
- 創(chuàng)建實(shí)現(xiàn)類
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("BeanPostProcessor 后處理Bean...");
}
public void myInit(){
System.out.println("初始化");
}
public void myDestroy(){
System.out.println("銷毀");
}
}
- 創(chuàng)建代理類
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("前方法: "+bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName)
throws BeansException {
System.out.println("后方法: "+beanName);
// bean 目標(biāo)對(duì)象
// 生成 jdk 代理
return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(),
bean.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("開啟事務(wù)");
//執(zhí)行目標(biāo)方法
Object obj=method.invoke(bean, args);
System.out.println("提交事務(wù)");
return null;
}
});
}
}
- 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">
<!-- init-method 用于配置初始化方法,準(zhǔn)備數(shù)據(jù)等
destroy-method 用于配置銷毀方法,清理資源等 -->
<bean id="userServiceImplId" class="g_lifecycle_beanPostProcessor.UserServiceImpl" init-method="myInit" destroy-method="myDestroy"></bean>
<!-- 將后處理的實(shí)現(xiàn)類注冊(cè)給spring -->
<bean class="g_lifecycle_beanPostProcessor.MyBeanPostProcessor"></bean>
</beans>
- 測(cè)試
@org.junit.Test
public void test01() {
String xmlPath="g_lifecycle_beanPostProcessor/applicationContext.xml";
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
userService.addUser();
//使用ClassPathXmlApplicationContext調(diào)用close
applicationContext.close();
}
10 屬性的依賴注入
10.1 依賴注入方式
- 手動(dòng)裝配:一般進(jìn)行配置信息都采用手動(dòng)
- 基于xml裝配:構(gòu)造方法、setter方法
- 基于注解裝配
- 自動(dòng)裝配:struts和spring整合可以自動(dòng)裝配
- byType:按類型裝配
- byName:按名稱裝配
- constructor:構(gòu)造裝配
- auto:不確定裝配
10.2 構(gòu)造注入
- 創(chuàng)建實(shí)體類
public class User {
private int id;
private String name;
private int age;
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
- 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">
<!-- 構(gòu)造方法注入
<constructor-arg> 用于配置構(gòu)造方法一個(gè)參數(shù)argument
name :參數(shù)的名稱
value:設(shè)置普通數(shù)據(jù)
ref:引用數(shù)據(jù),一般是另一個(gè)bean id值
index :參數(shù)的索引號(hào),從0開始 。如果只有索引,匹配到了多個(gè)構(gòu)造方法時(shí),默認(rèn)使用第一個(gè)。
type :確定參數(shù)類型
例如:使用名稱name
<constructor-arg name="username" value="jack"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
例如2:類型type 和 索引 index
<constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
<constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
-->
<bean id="userId" class="h_gouZao.User">
<constructor-arg index="0" type="String" value="張三"></constructor-arg>
<constructor-arg index="1" type="int" value="25"></constructor-arg>
</bean>
</beans>
- 測(cè)試
@org.junit.Test
public void test01() {
String xmlPath="h_gouZao/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
User u=(User) applicationContext.getBean("userId");
System.out.println(u);
}
10.3 setter注入
- address實(shí)體類
public class Address {
private String addr;
private int tel;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Address [add=" + addr + ", tel=" + tel + "]";
}
}
- person實(shí)體類
public class Person {
private String name;
private int age;
private Address homeAddr;
private Address companyAddr;
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;
}
public Address getHomeAddr() {
return homeAddr;
}
public void setHomeAddr(Address homeAddr) {
this.homeAddr = homeAddr;
}
public Address getCompanyAddr() {
return companyAddr;
}
public void setCompanyAddr(Address companyAddr) {
this.companyAddr = companyAddr;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", homeAddr="
+ homeAddr + ", companyAddr=" + companyAddr + "]";
}
}
- 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">
<!-- setter方法注入
* 普通數(shù)據(jù)
<property name="" value="值">
等效
<property name="">
<value>值</value>
</property>
* 引用數(shù)據(jù)
<property name="" ref="另一個(gè)bean">
等效
<property name="">
<ref bean="另一個(gè)bean"/>
-->
<bean id="personId" class="i_setter.Person">
<property name="name" value="張三"></property>
<property name="age" value="23"></property>
<property name="homeAddr" ref="homeAddrId"></property>
<property name="companyAddr" ref="companyAddrId"></property>
</bean>
<bean id="homeAddrId" class="i_setter.Address">
<property name="addr" value="上海"></property>
<property name="tel" value="163"></property>
</bean>
<bean id="companyAddrId" class="i_setter.Address">
<property name="addr" value="南京"></property>
<property name="tel" value="126"></property>
</bean>
</beans>
- 測(cè)試
@org.junit.Test
public void test01() {
String xmlPath="i_setter/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
Person p=(Person) applicationContext.getBean("personId");
System.out.println(p);
}
10.4 P命名空間
- 對(duì)“setter方法注入”進(jìn)行簡(jiǎn)化,替換
<property name="屬性名">,而是在<bean p:屬性名="普通值" p:屬性名-ref="引用值"> - P命名空間使用前提,必須添加命名空間
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
1. P命名空間使用前需添加命名空間: xmlns:p="http://www.springframework.org/schema/p"
2. <bean p:屬性名="普通值" p:屬性名-ref="引用值">
-->
<bean id="personId" class="j_p.Person"
p:name="張三" p:age="23"
p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId"></bean>
<bean id="homeAddrId" class="j_p.Address" p:addr="上海" p:tel="12345678"></bean>
<bean id="companyAddrId" class="j_p.Address" p:addr="南京" p:tel="666"></bean>
</beans>
10.5 集合注入
<?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">
<!--
集合的注入都是給<property>添加子標(biāo)簽
數(shù)組:<array>
List:<list>
Set:<set>
Map:<map> ,map存放k/v 鍵值對(duì),使用<entry>描述
Properties:<props> <prop key=""></prop>
普通數(shù)據(jù):<value>
引用數(shù)據(jù):<ref>
-->
<bean id="collDataId" class="k_coll.CollData" >
<property name="arrayData">
<array>
<value>DS</value>
<value>DZD</value>
<value>屌絲</value>
<value>屌中屌</value>
</array>
</property>
<property name="listData">
<list>
<value>姓名1</value>
<value>姓名2</value>
<value>姓名3</value>
</list>
</property>
<property name="setData">
<set>
<value>張三</value>
<value>李四</value>
<value>王五</value>
</set>
</property>
<property name="mapData">
<map>
<entry key="jack" value="杰克"></entry>
<entry>
<key><value>rose</value></key>
<value>肉絲</value>
</entry>
</map>
</property>
<property name="propsData">
<props>
<prop key="高富帥">嫐</prop>
<prop key="白富美">嬲</prop>
<prop key="男屌絲">挊</prop>
</props>
</property>
</bean>
</beans>
10.6 SpEl
- 對(duì)<property>進(jìn)行統(tǒng)一編程,所有的內(nèi)容都使用value
<property name="" value="#{表達(dá)式}">-
#{123}、#{'jack'}數(shù)字、字符串 -
#{beanId}另一個(gè)bean引用 -
#{beanId.propName}操作數(shù)據(jù) -
#{beanId.toString()}執(zhí)行方法 -
#{T(類).字段|方法}靜態(tài)方法或字段
<!--
<property name="cname" value="#{'jack'}"></property>
<property name="cname" value="#{customerId.cname.toUpperCase()}"></property>
通過(guò)另一個(gè)bean,獲得屬性,調(diào)用的方法
<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
?. 如果對(duì)象不為null,將調(diào)用方法
-->
<bean id="customerId" class="com.itheima.f_xml.d_spel.Customer" >
<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
<property name="pi" value="#{T(java.lang.Math).PI}"></property>
</bean>
11 基于注解
11.1 注解分類
-
@Component("id")取代<bean id="" class=""> - web開發(fā),提供3個(gè)
@Component注解衍生注解(功能一樣)取代<bean class="">-
@Repositorydao層 -
@Serviceservice層 -
@Controllerweb層
-
- 依賴注入,給私有字段設(shè)置,也可以給setter方法設(shè)置
- 普通值使用
@Value("") - 引用值
- 按照類型注入
@Autowired - 按照名稱注入
@Autowired @Qualifier("名稱") - 按照名稱注入
@Resource("名稱"),此注解由jdk提供,以上兩個(gè)注解則由spring提供
- 按照類型注入
- 普通值使用
- 生命周期注解
- 初始化
@PostConstruct - 銷毀
@PreDestroy
- 初始化
- 作用域注解
- 多例
@Scope("prototype") - 單例
@Scope("singleton")
- 多例
11.2 注解示例
- xml配置
- 使用注解類前需添加命名空間,讓spring掃描含有注解類
xmlns:context="http://www.springframework.org/schema/context"http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
<?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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="m_zhuJie02"></context:component-scan>
</beans>
- 測(cè)試類
- 加載配置文件,根據(jù)
StudentActionID找到控制層
- 加載配置文件,根據(jù)
@org.junit.Test
public void test01(){
String xmlPath="m_zhuJie02/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
StudentAction studentAction=(StudentAction) applicationContext.getBean("StudentActionID");
studentAction.execute();
}
- action控制層
- 控制層依賴service業(yè)務(wù)層,將業(yè)務(wù)層按照類型注入,也可以按照名稱注入
@Controller("StudentActionID")
public class StudentAction {
//按照類型注入
@Autowired
private StudentService studentService;
public void execute(){
studentService.addStudent();
}
}
- service實(shí)現(xiàn)類
- service業(yè)務(wù)層依賴dao數(shù)據(jù)層,將dao注入給service
@Service
public class StudentServiceImpl implements StudentService {
// @Qualifier("studentDaoID")
// @Autowired
@Resource(name="studentDaoID")
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public void addStudent() {
studentDao.save();
}
}
- dao實(shí)現(xiàn)類
@Repository("studentDaoID")
public class StudentDaoImpl implements StudentDao {
@Override
public void save() {
System.out.println("dao");
}
}

