spring框架概述&IOC理解

一、spring框架概述

1.什么是spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。Spring的核心是控制反转(IoC)和面向切面(AOP)。简单来说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架。

轻量级:spring是一个轻量级的开发框架,这个是相对于EJB来说的,因为spring依赖的资源少,销毁的资源也少。

分层架构:因为spring每一个层都提供有解决方案,而不是统一做一个解决方案,正因为spring每一层都有解决方案,所有spring也是一个一站式开源框架。web层:springMVC;service层:spring;dao层:springData。

2.Spring优点
  • 方便解耦,简化开发(高内聚低耦合)
    spring就是一个大工厂(容器),可以将所有对象创建和依赖关系维护,交给spring管理,spring工厂是用于生成bean
  • AOP编程的支持
    spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
  • 声明式事务的支持
    只需要通过配置就可以完成对事务的管理,而无需手动编程
  • 方便程序的测试
    spring对Junit4支持,可以通过注解方便的测试spring程序
  • 方便集成各种优秀框架
    spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架的直接支持(如:Struts、Hibernate、Mybatis、Quartz)
  • 降低JavaEE API的使用难度
    spring对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低
3.Spring体系结构

核心容器:beans、core、context、expression

二、IOC入门案例

1.导入jar包

4+1: 4个核心(beans、core、context、expression)+1个依赖(commons-loggins…jar)如下图:
在这里插入图片描述
在这里插入图片描述

2.创建目标类

创建UserService接口类:

public interface UserService {
	
	public void addUser();

}

创建UserServiceImpl实现类:

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("a_ico add user");
	}

}
3.配置文件

位置:任意,开发中一般在classpath下(src文件下)
名称:任意,开发中约定俗成用:applicationContext.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">
	<!-- 配置service 
		<bean> 配置需要创建的对象
			id :用于之后从spring容器获得实例时使用的
			class :需要创建实例的全限定类名
	-->
	<bean id="userServiceId" class="com.itheima.a_ioc.UserServiceImpl"></bean>
</beans>
4.测试

之前开发中,直接new一个对象即可;使用spring之后,将由spring创建对象实例,之后需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中。

	@Test
	public void demo02(){
		//从spring容器获得
		//1 获得容器
		String xmlPath = "com/itheima/a_ioc/beans.xml";//spring配置文件路径
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//2获得内容 --不需要自己new,都是从spring容器获得
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
		
	}

三、DI入门案例

DI (Dependency Injection):依赖注入;
is a :是一个, 继承关系
has a:有一个,成员变量,依赖关系;如:

		class B {
           private A a;   //B类依赖A类
        }

依赖:一个对象需要使用另一个对象;
注入:本例中使用setter方法进行另一个对象实例设置;例如:

	class BookServiceImpl{
        //之前开发:接口 = 实现类  (service和dao耦合)
		//private BookDao bookDao = new BookDaoImpl();
 		//spring之后 (解耦:service实现类使用dao接口,不知道具体的实现类)
		private BookDao bookDao;
		setter方法
   }

模拟spring执行原理过程:
创建service实例:BookService bookService = new BookServiceImpl() -->IOC
创建dao实例:BookDao bookDao = new BookDaoImple() -->IOC
将dao设置给service:bookService.setBookDao(bookDao) -->DI

1.创建目标类

创建BookDao接口:

public interface BookDao {
	
	public void save();

}

创建BookDao实现类:

public class BookDaoImpl implements BookDao {

	@Override
	public void save() {
		System.out.println("di  add book");
	}

}

创建BookService接口类:

public interface BookService {

	public abstract void addBook();

}

创建BookService实现类,注意添加setBookDao()方法用于spring依赖注入:

public class BookServiceImpl implements BookService {
	
	// 方式1:之前,接口=实现类
//	private BookDao bookDao = new BookDaoImpl();
	// 方式2:接口 + setter
	private BookDao bookDao;
	
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}
	
	@Override
	public void addBook(){
		this.bookDao.save();
	}

	public BookServiceImpl() {
		System.out.println("被new 了");
	}
	
}
2.配置文件

配置文件多加了property标签,用于属性注入:

<?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执行过程
		创建service实例:BookService bookService = new BookServiceImpl()	IoC  <bean>
		创建dao实例:BookDao bookDao = new BookDaoImpl()			IoC
		将dao设置给service:bookService.setBookDao(bookDao);		DI   <property>
		
		<property> 用于进行属性注入
			name: bean的属性名,通过setter方法获得
				setBookDao ##> BookDao  ##> bookDao
			ref :另一个bean的id值的引用
	 -->

	<!-- 创建service -->
	<bean id="bookServiceId" class="com.itheima.b_di.BookServiceImpl" >
		<property name="bookDao" ref="bookDaoId"></property>
	</bean>
	
	<!-- 创建dao实例 -->
	<bean id="bookDaoId" class="com.itheima.b_di.BookDaoImpl"></bean>
	
</beans>
3.测试

创建测试类,这里为了理解ApplicationContext与BeanFactory两个接口的区别,所以使用了两个测试方法。
ApplicationContext测试方法:

	@Test
	public void demo01(){
		//从spring容器获得
		String xmlPath = "com/itheima/b_di/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		BookService bookService = (BookService) applicationContext.getBean("bookServiceId");
		
		bookService.addBook();
		
	}

BeanFactory测试方法:

	@Test
	public void demo02(){
		//使用BeanFactory  --第一次条用getBean实例化
		String xmlPath = "com/itheima/b_di/beans.xml";
		
		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
		
		BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
		
		bookService.addBook();
		
	}

四、核心API

spring API 架构图:

BeanFactory :这是一个工厂,用于生成任意bean。采取延迟加载,第一次getBean 时才会初始化bean;

ApplicationContext:是BeanFactory的子接口,功能更加强大。(国际化处理、事件传递、Bean自动装配、各种不同应用层的Context实现)当配置文件被加载时,就进行对象的实例化。

ClassPathXmlApplicationContext :该实现类用于加载classpath(类路径、src)下的xml;加载xml运行时位置—>/WEB-INF/classes/…xml

FileSystemXmlApplicationContext :该实现类用于加载指定盘符下的xml;加载xml运行时位置---->/WEB-INF/…xml

五、装配Bean基于XML

1.实例化方式

3种Bean实例化方式:默认构造、静态工厂、实例工厂

默认构造
<bean id="" class=""> 必须提供默认构造方法,不可没有无参构造方法。

静态工厂
该方法常用于spring整合其他框架(工具)。静态工厂:用于生成实例对象,所有的方法必须是static。

<bean id=""  class="工厂全限定类名"  factory-method="静态方法">

该例子自己定义了一个MyBeanFactory 静态工厂对象,用于生成UserServiceImpl实例对象。具体例子如下:

创建MyBeanFactory 对象,注意对象中的方法为静态方法:

public class MyBeanFactory {
	/**
	 * 创建实例
	 * @return
	 */
	public static UserService createService(){
		return new UserServiceImpl();
	}
}

配置文件:

<?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 
		class 确定静态工厂全限定类名
		factory-method 确定静态方法名
	-->
	<bean id="userServiceId" class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>

</beans>

测试:

	@Test
	public void demo02(){
		//spring 工厂
		String xmlPath = "com/itheima/c_inject/b_static_factory/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);
		userService.addUser();
	}

实例工厂
实例工厂:必须先有工厂实例对象,通过实例对象创建对象。提供的所有方法都是 “ 非静态 ” 的。例子如下:

创建实例工厂:

/**
 * 实例工厂,所有方法非静态
 *
 */
public class MyBeanFactory {
	
	/**
	 * 创建实例
	 * @return
	 */
	public UserService createService(){
		return new UserServiceImpl();
	}
}

配置文件:

<?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="myBeanFactoryId" class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>
	<!-- 获得userservice 
		* factory-bean 确定工厂实例
		* factory-method 确定普通方法
	-->
	<bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>
	
</beans>
2.Bean种类
  • 普通bean:之前操作的都是普通bean。<bean id="" class="A"> spring直接创建A实例,并返回。
  • FactoryBean:是一个特殊的bean,具有工厂生成对象的能力,只能生成特定的对象。bean必须使用FactoryBean接口,此接口提供方法getObject()用于获得特定bean。
  • BeanFactory 和 FactoryBean 对比:
    BeanFactory :工厂,用于生成任意bean;
    FactoryBean :特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean ,此工厂bean用于生产代理。<bean id="" class="....ProxyFactoryBean"> 获得代理对象实例。AOP使用
    BeanFactory 和 FactoryBean两个都是接口类
3.作用域

作用域:用于确定spring创建bean实例个数:
在这里插入图片描述
取值
singleton 单例,默认值
prototype 多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例。
配置信息
在这里插入图片描述

4.生命周期

初始化和销毁
当spring容器启动时,bean对象被实例化之后执行初始化方法,当spring容器关闭时,执行销毁方法。

<bean id="" class="" init-method="初始化方法名称"  destroy-method="销毁的方法名称">

例子如下:
创建目标接口类:

public interface UserService {
	
	public void addUser();

}

创建目标实现类:

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("e_lifecycle add user");
	}
	
	public void myInit(){
		System.out.println("初始化");
	}
	public void myDestroy(){
		System.out.println("销毁");
	}

}

配置文件:

<?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 用于配置初始化方法,准备数据等
		destroy-method 用于配置销毁方法,清理资源等
	-->
	<bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl" 
		init-method="myInit" destroy-method="myDestroy" ></bean>
</beans>

测试类:

@Test
	public void demo02() throws Exception{
		//spring 工厂
		String xmlPath = "com/itheima/e_lifecycle/beans.xml";
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
		
		//要求:1.容器必须close,销毁方法执行; 2.必须是单例的
//		applicationContext.getClass().getMethod("close").invoke(applicationContext);
		// * 此方法接口中没有定义,实现类提供
		applicationContext.close();
		
	}

测试结果:

BeanPostProcessor 后处理Bean
spring提供了一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,spring将自动执行,在初始化方法前执行postProcessBeforeInitialization()方法,在初始化方法后执行postProcessAfterInitialization()方法。

Factory hook that allows for custom modification of new bean instances, e.g. checking for marker interfaces or wrapping them with proxies.
译:spring提供工厂勾子,用于修改实例对象,可以生成代理对象,是AOP底层。

现在我们举一个例子,目的就是在实例对象的目标方法前后执行方法,比如说事务处理。为了方便理解,下面模拟spring执行流程:

A a =new A();
a = B.before(a)			// 将a的实例对象传递给后处理bean,可以生成代理对象并返回。
a.init();
a = B.after(a);
//开启事务
a.addUser();		//目标方法,生成代理对象,目的在目标方法前后执行(例如:开启事务、提交事务)
//提交事务
a.destroy()

创建目标接口类:

public interface UserService {
	
	public void addUser();
}

创建目标实现类(注意:接口类里并没有初始化方法和销毁方法,):

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("e_lifecycle add user");
	}
	
	public void myInit(){
		System.out.println("初始化");
	}
	public void myDestroy(){
		System.out.println("销毁");
	}

	public UserServiceImpl() {
		System.out.println("实例化");
	}
	
}

编写后处理Bean实现类:

public class MyBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("前方法 : " + beanName);
		return bean;
		
	}

	@Override
	public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
		System.out.println("后方法 : " + beanName);
		// bean 目标对象
		// 生成 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("------开启事务");
						
						//执行目标方法
						Object obj = method.invoke(bean, args);
						
						System.out.println("------提交事务");
						return obj;
					}});
	}
}

这里把生成代理对象放在后postProcessAfterInitialization()方法中,如果放在postProcessBeforeInitialization()方法中,由于代理对象执行的是接口中的方法,所以也必须要在接口中添加初始化方法,注重理解此处,而不用添加销毁方法,因为对象的销毁与代理对象无关。

配置文件(将后处理Bean实现类交给spring管理):

<?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 用于配置初始化方法,准备数据等
		destroy-method 用于配置销毁方法,清理资源等
	-->
	<bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl" 
		init-method="myInit" destroy-method="myDestroy" ></bean>
	
	<!-- 将后处理的实现类注册给spring -->
	<bean class="com.itheima.e_lifecycle.MyBeanPostProcessor"></bean> 
</beans>

编写测试类:

	@Test
	public void demo02() throws Exception{
		//spring 工厂
		String xmlPath = "com/itheima/e_lifecycle/beans.xml";
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
		
		//要求:1.容器必须close,销毁方法执行; 2.必须是单例的
//		applicationContext.getClass().getMethod("close").invoke(applicationContext);
		// * 此方法接口中没有定义,实现类提供
		applicationContext.close();
		
	}

测试结果:

5.属性依赖注入

依赖注入方式:手动装配、自动装配

手动装配:一般进行配置信息都采用手动

  • 基于xml装配:构造方法、setter方法
  • 基于注解装配

自动装配:Struts和spring整合可以自动装配

  • byType:按类型装配
  • byName:按名称装配
  • constructor:构造装配
  • aoto:不确定装配

构造方法依赖注入
创建目标类,并自行重写带参数构造方法(不需要setter、getter方法):

public class User {
	
	private Integer uid;
	private String username;
	private Integer age;
	
	public User(Integer uid, String username) {
		super();
		this.uid = uid;
		this.username = username;
	}
	
	public User(String username, Integer age) {
		super();
		this.username = username;
		this.age = age;
	}
}

配置文件:

<?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">

	<!-- 构造方法注入 
		* <constructor-arg> 用于配置构造方法一个参数argument
			name :参数的名称
			value:设置普通数据
			ref:引用数据,一般是另一个bean id值
			
			index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
			type :确定参数类型
		例如:使用名称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="com.itheima.f_xml.a_constructor.User" >
		<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>
</beans>

测试类:

	@Test
	public void demo02() throws Exception{
		//spring 工厂
		String xmlPath = "com/itheima/f_xml/a_constructor/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		User user = (User) applicationContext.getBean("userId");
		System.out.println(user);
	}

测试结果:

setter方法依赖注入
此处逻辑与上面差不多,所有只显示配置文件:

<?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方法注入 
		* 普通数据 
			<property name="" value="值">
			等效
			<property name="">
				<value>值
		* 引用数据
			<property name="" ref="另一个bean">
			等效
			<property name="">
				<ref bean="另一个bean"/>
	
	-->
	<bean id="personId" class="com.itheima.f_xml.b_setter.Person">
		<property name="pname" value="小明"></property>
		<property name="age">
			<value>1234</value>
		</property>
		
		<property name="homeAddr" ref="homeAddrId"></property>
		<property name="companyAddr">
			<ref bean="companyAddrId"/>
		</property>
	</bean>
	
	<bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address">
		<property name="addr" value="北京"></property>
		<property name="tel" value="911"></property>
	</bean>
	<bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address">
		<property name="addr" value="北京"></property>
		<property name="tel" value="120"></property>
	</bean>
	
</beans>

P命名空间(对setter方法注入进行了简化)
P命名空间方法是对setter方法进行了简化,替换<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">
	
	<bean id="personId" class="com.itheima.f_xml.c_p.Person" 
		p:pname="小明" p:age="22" 
		p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
	</bean>
	
	<bean id="homeAddrId" class="com.itheima.f_xml.c_p.Address"
		p:addr="yy" p:tel="111">
	</bean>
	<bean id="companyAddrId" class="com.itheima.f_xml.c_p.Address"
		p:addr="hh" p:tel="222">
	</bean>
	
</beans>

SpEL
<property>进行统一编程,所有的内容都使用value

<property name="" value="#{表达式}">

#{123}、#{‘jack’} : 数字、字符串
#{beanId} :另一个bean引用
#{beanId.propName} :操作数据
#{beanId.toString()} :执行方法
#{T(类).字段|方法} :静态方法或字段
下面为具体例子:

创建java bean对象:

public class Customer {
	
	private String cname = "jack";
	private Double pi ;// = Math.PI;
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Double getPi() {
		return pi;
	}
	public void setPi(Double pi) {
		this.pi = pi;
	}
	@Override
	public String toString() {
		return "Customer [cname=" + cname + ", pi=" + pi + "]";
	}
	

}

配置文件:

<?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 name="cname" value="#{'jack'}"></property>
		<property name="cname" value="#{customerId.cname.toUpperCase()}"></property>
			通过另一个bean,获得属性,调用的方法
		<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
			?.  如果对象不为null,将调用方法
	-->
	<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>
</beans>

测试类:

@Test
	public void demo02() throws Exception{
		//spring 工厂
		String xmlPath = "com/itheima/f_xml/d_spel/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		Customer customer = (Customer) applicationContext.getBean("customerId");
		System.out.println(customer);
	}

测试结果:

集合注入
集合的注入都是给<property>添加子标签,例子如下:

创建java bean对象:

public class CollData {
	
	private String[] arrayData;
	private List<String> listData;
	private Set<String> setData;
	private Map<String, String> mapData;
	private Properties propsData;
	
	
	public String[] getArrayData() {
		return arrayData;
	}
	public void setArrayData(String[] arrayData) {
		this.arrayData = arrayData;
	}
	public List<String> getListData() {
		return listData;
	}
	public void setListData(List<String> listData) {
		this.listData = listData;
	}
	public Set<String> getSetData() {
		return setData;
	}
	public void setSetData(Set<String> setData) {
		this.setData = setData;
	}
	public Map<String, String> getMapData() {
		return mapData;
	}
	public void setMapData(Map<String, String> mapData) {
		this.mapData = mapData;
	}
	public Properties getPropsData() {
		return propsData;
	}
	public void setPropsData(Properties propsData) {
		this.propsData = propsData;
	}
	@Override
	public String toString() {
		return "CollData [\narrayData=" + Arrays.toString(arrayData) + ", \nlistData=" + listData + ", \nsetData=" + setData + ", \nmapData=" + mapData + ", \npropsData=" + propsData + "\n]";
	}
	
	
}

配置文件:

<?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>添加子标签
			数组:<array>
			List:<list>
			Set:<set>
			Map:<map> ,map存放k/v 键值对,使用<entry>描述
			Properties:<props>  <prop key=""></prop>  【】
			
		普通数据:<value>
		引用数据:<ref>
	-->
	<bean id="collDataId" class="com.itheima.f_xml.e_coll.CollData" >
		<property name="arrayData">
			<array>
				<value>DS</value>
				<value>DZD</value>
				<value>屌丝</value>
				<value>屌中屌</value>
			</array>
		</property>
		
		<property name="listData">
			<list>
				<value>于嵩楠</value>
				<value>曾卫</value>
				<value>杨煜</value>
				<value>曾小贤</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>

测试类:

	@Test
	public void demo02() throws Exception{
		//spring 工厂
		String xmlPath = "com/itheima/f_xml/e_coll/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		CollData collData = (CollData) applicationContext.getBean("collDataId");
		System.out.println(collData);
	}

测试结果:

六、装配Bean基于注解

注解就是一个类,使用:@注解名称
开发中,一般都是使用注解取代xml配置文件

  1. @Component (组件)取代<bean class="">;@Component(“id”) 取代<bean id="" class="">,对任意bean都起作用。
  2. web开发中,根据分层提供3个@Component注解的衍生注解(功能一样)取代<bean class="">
    @Repository:dao层
    @Service:service层
    @Controller:web层
  3. 依赖注入,给私有字段设置,也可以给setter方法设置。
    普通值:@Value("")
    引用值:(如果不设置值,默认bean的id为类名首字母小写)
    方式1:按照【类型】注入:
    @Autowired
    方式2:按照【名称】注入1:
    @Autowired
    @Qualifier(“名称”)
    方式3:按照【名称】注入2:
    @Resource(“名称”)
  4. 生命周期
    初始化:@PostConstruct
    销毁:@PreDestroy
  5. 作用域
    @Scope(“prototype”) 多例

注意:注解使用前提,添加命名空间,让spring扫描含有注解类
在这里插入图片描述配置文件:

<?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="com.itheima.g_annotation.a_ioc"></context:component-scan>
</beans>
注解和XML混合使用

在有的开发中,使用注解与XML混合使用,具体如下:
将所有的bean都配置到XML中,<bean id="" class="">
将所有的依赖都使用注解:
@Autowired
默认不生效,为了生效,需要在xml中配置:<context:annotation-config>
总结:
注解1:<context:component-scan base-package=" ">
注解2:<context:annotation-config>

一般情况下两个注解不一起使用;
“注解1”扫描含有注解(@Component、@Controller 等)类,依赖注入注解自动生效;
“注解2”只在xml和注解(注入)混合使用时,使注入注解生效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值