【Spring笔记1】JavaWeb的三层结构以及Spring IOC、DI详解

目录

1.JavaWeb项目的三层结构

2.Spring基础学习

2.1 Spring基础知识

2.2 IoC(掌握)

2.3 DI(掌握)

2.4 核心API(了解) 

2.5 装配Bean基于XML 

2.5.1实例化方式

2.5.2 bean种类和作用域

2.5.3 生命周期

2.5.4 bean装配基于XML的属性注入

2.6 装配Bean基于注解(掌握)

2.6.1 使用@Component

2.6.2 Web开发的注解

2.6.3 生命周期和作用域相关的注解


1.JavaWeb项目的三层结构

JavaWeb三层结构包括:web层(也叫表示层)、service层(也叫业务逻辑层)、dao层(也叫数据访问层)

web层使用的框架有struts、spring mvc,service层使用spring框架,dao层使用hibernate或者mybatis框架。我们所说的SSM框架也就是Spring+Spring MVC+MyBatis的缩写。

浏览器访问服务器上的Web层,三层结构表示图如下所示,其中Spring贯穿三层,起到承前启后的作用。而浏览器通常使用JavaScript和jQuery框架。

Spring的学习过程主要分三个阶段:

阶段一:基础学习(IoC控制翻转,DI依赖注入),Spring整合Junit,Spring整合web

阶段二:AOP面向切面编程、JdbcTemplate

阶段三:事务管理、SSH整合

2.Spring基础学习

2.1 Spring基础知识

说明:Eclipse和MyEclipse为开发Java的工具,Eclipse允许安装第三方插件来扩展自己的功能,而MyEclipse可以理解为一个插件集,是在Eclipse上的一个扩展,专用于J2EE的开发。Eclipse包括了MyEclipse,功能更强大,我们可以由MyEclipse开发转为直接用Eclipse开发。

什么是Spring?

Spring是一个开源的轻量级Java开发框架,它是为了解决企业开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只能由EJB完成的事情。Spring的主要优势就是其分层结构,它是一个分层的Java SE/EE full-stack(一站式)开源框架。

轻量级是相对于EJB(Enterprise JavaBean:企业级JavaBean)而言的,其依赖资源少,消耗资源少。

Spring框架由七个定义明确的模块组成:核心容器(Spring Core)、应用上下文模块(Spring Context)、Spring的AOP模块(Spring AOP)、JDBC抽象和DAO模块(Spring DAO)、对象/关系映射集成模块(Spring ORM)、Spring的Web模块(Spring Web)、Spring的MVC模块(Spring  Web MVC)

Spring的体系结构

Spring的核心

  • Spring的核心是控制反转(IoC)面向切面(AOP)

Spring的优点

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

2.2 IoC(掌握)

1.MyEclipse(或者Eclipse)创建web project

2.导入jar包(4+1,  4个核心:beans、core、context、expression,1个依赖:common-loggings)

这里用的是spring-framework-3.2.0.RELEASE-dist.zip的jar包和spring-framework-3.0.2.RELEASE-dependencies.zip

导jar包的时候别导错了(xxx-sources.jar表示的是源码,xxx.RELEASE.jar表示的是字节码)

 

3.添加目标类(抽象类和实现类)

package com.syc.a_ioc;

public interface UserService {
	public void addUser();

}
package com.syc.a_ioc;

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		// TODO Auto-generated method stub
		System.out.println("a_ioc add user");

	}

}

4.添加配置文件

位置:任意,一般放在classpath下

名称:任意,约定取applicationContext.xml,这里取beans.xml

内容:添加schema约束

约束文件位置:spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html

* 配置约束文件的方式:Window->Preferences->搜索xml catalog->add ->File system选好后,key type 选择scheme location,将http://www.springframework.org/schema/beans/spring-beans.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"
       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.syc.a_ioc.UserServiceImpl"></bean>

</beans>

 5.测试

package com.syc.a_ioc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIoC {
	@Test
	public void demo01(){
		//之前new方法
		UserService userService = new UserServiceImpl();
		userService.addUser();
	}
	
	@Test
	public void demo02(){
		//从Spring容器获得
		//1.获得容器
		String xmlPath = "com/syc/a_ioc/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//2.获得内容,不需要自己new,直接从容器中获得
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
	}

}

demo01运行结果:

demo02运行结果:

2.3 DI(掌握)

1.DI解释

DI全称为Dependency Injection,依赖注入。什么是依赖注入呢?

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  <bean>

       创建dao实例:BookDao bookDao = new BookDaoImple() ;                          -->IoC

       将dao设置给service:bookService.setBookDao(bookDao);                         -->DI   <property>

2.Dao

public interface BookDao {
	public void addBook();

}
public class BookDaoImpl implements BookDao {

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

	}

}

3.Service 

public interface BookService {

	public abstract void addBook();

}
public class BookServiceImpl implements BookService {	
	/*
	 * 
	//方法1:以前的方法,接口=实现类
	private BookDao bookDao = new BookDaoImpl();
		
	@Test
	@Override
	public void addBook(){
		bookDao.addBook();		
	}
	*/
	
	//方法2:基于setter方法的依赖注入	
	//接口+setter方法
	private BookDao bookDao;
	public void setBook(BookDao bookDao) {
		this.bookDao = bookDao;
	}
	@Override
	public void addBook() {
		bookDao.addBook();
		
	}
}

 4.配置文件

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

<!-- 
	两个IoC来获取bean,
	Property进行属性输入,name为set方法的变形:SetBook->Book->book
        ref为另一个bean的id值的引用
 -->
<bean id="bookServiceId" class="com.syc.b_di.BookServiceImpl">
	<property name="book" ref="bookDaoId"></property>
</bean>

<bean id="bookDaoId" class="com.syc.b_di.BookDaoImpl"></bean>

</beans>

5.测试

public class TestDI {

	@Test
	public void demo01(){
		//从Spring容器获得
		//1.获得容器
		String xmlPath = "com/syc/b_di/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//2.获得内容,不需要自己new,直接从容器中获得
		BookService bookService = (BookService) applicationContext.getBean("bookServiceId");
		bookService.addBook();
	}

}

2.4 核心API(了解) 

  • BeanFactory:这是一个工厂,用于生成任意bean

       采取延迟加载,第一次getBean时才会初始化Bean

  • ApplicationContext:是BeanFactory的子接口,功能更强大。当配置文件被加载,就进行对象实例化。

       ClassPathXmlApplicationContext 用于加载classpath(即类路径、src)下的xml

       FileSystemXmlApplicationContext 用于加载指定盘符下的xml

        @Test
	public void demo02(){
		//使用BeanFactory,第一次调用getBean时才被实例化
		//1.获得容器
		String xmlPath = "com/syc/b_di/beans.xml";		
		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
		//2.获得内容,不需要自己new,直接从容器中获得
		BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
		bookService.addBook();
	}

2.5 装配Bean基于XML 

2.5.1实例化方式

对象的实例化方式有三种:默认构造、静态工厂、实例工厂

1.默认构造

在上面所提到的IoC、DI中,使用下面的结构要求在实现类中必须有一个默认的构造器,否则报错

<bean id="" class="" ></bean>

2.静态工厂

工厂是用于生产实例对象的,所有的方法必须是静态的

public class MyBeanFactory {
	
	public static UserService createService(){
		return new UserServiceImpl();
	}

}
public interface UserService {
	public void addUser();

}
public class UserServiceImpl implements UserService {

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

}

配置文件beans.xml的写法:<bean id="对象名" class="工厂的全限定类名" factory-method="静态方法名"/>

<?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="userServiceId" class="com.syc.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>

</beans>

测试类:

public class TestStaticFactory {
	//以前的方法
	@Test
	public void demo01() {
		MyBeanFactory.createService().addUser();
	}
	
	//使用spring的静态工厂
	@Test
	public void demo02(){
		String xmlPath = "com/syc/c_inject/b_static_factory/beans.xml";
		ApplicationContext application = new ClassPathXmlApplicationContext(xmlPath);
		//获得内容,不用每次都强制转换,加上类型即可
		UserService userService = application.getBean("userServiceId", UserService.class);
		userService.addUser();
	}
}

3.实例工厂

实例工厂:必须现有实例工厂对象,通过实例对象创建对象,实例工厂中所有的方法必须是非静态的

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

}

Service与实现类与上面的相似,配置文件如下形式<bean id=" " factory-bean="工厂实例名称" factory-method="工厂方法"/>

factory-bean:确定工厂实例,factory-method:确定普通方法

<?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.syc.c_inject.c_factory.MyBeanFactory"></bean>

<bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>

</beans>

测试类:

public class TestFactory {
	//以前的方法
	@Test
	public void demo01() {
		MyBeanFactory myBeanFactory = new MyBeanFactory();
		myBeanFactory.createService().addUser();
	}
	
	//使用spring的实例工厂
	@Test
	public void demo02(){
		String xmlPath = "com/syc/c_inject/c_factory/beans.xml";
		ApplicationContext application = new ClassPathXmlApplicationContext(xmlPath);
		//获得内容,不用每次都强制转换,加上类型即可
		UserService userService = application.getBean("userServiceId", UserService.class);
		userService.addUser();
	}
}

2.5.2 bean种类和作用域

1.bean种类

  • 普通bean: <bean id="" class="A"/>,直接创建A实例并返回
  • FactoryBean:是一个特殊的bean,具有工厂生产对象的能力,只能生产特定的对象。bean必须使用 FactoryBean接口,此接口提供方法 getObject() 用于获得特定bean。

       例如:ProxyFactoryBean,此工厂bean用于生产代理bean。通过配置<bean id="" class="...ProxyFactoryBean"/>直接过得代理对象实例。AOP中使用。

2.bean作用域

作用域:用于确定Spring创建bean实例个数

取值:

singleton:单例,默认值,只产生一个实例

prototype:多例,每次调用getBean()时,都产生一个实例

例如:单例情况

public class TestIoc {
	
	@Test
	public void demo01(){
		String xmlPath = "com/syc/d_scope/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

		UserService userService1 = applicationContext.getBean("userServiceId", UserService.class);
		UserService userService2 =  applicationContext.getBean("userServiceId", UserService.class);
		System.out.println(userService1);
		System.out.println(userService2);
	}
}

多例情况

<bean id="userServiceId" class="com.syc.d_scope.UserServiceImpl" scope="prototype"></bean>

2.5.3 生命周期

1.初始化和销毁

初始化和销毁方法在目标方法执行前后执行

目标类:

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("销毁");
	}
}

Spring配置:

<bean id="userServiceId" class="com.syc.e_lifecycle.UserServiceImpl" 
	init-method="myInit" destroy-method="myDestroy"></bean>

测试类:

public class TestCycle {
	
	@Test
	public void demo01(){
		String xmlPath = "com/syc/e_lifecycle/beans.xml";
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
		
		//要求:1.要执行销毁方法,容器必须关闭;2.必须是单例的        
		applicationContext.close();//ApplicationContext接口中没有close()方法
	}
}

执行结果:

2.BeanPostProcessor后处理Bean 

需要实现BeanPostProcessor接口,并将实现类提供给容器,容器将自动执行。在初始化方法前执行postProcessBeforeInitialization()方法,在初始化方法后执行postProcessAfterInitialization()方法。

实现类:

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(Object bean, String beanName)
			throws BeansException {
		System.out.println("后方法:" + beanName);
		return bean;
	}	
}

Spring配置中添加

<bean id="userServiceId" class="com.syc.e_lifecycle.UserServiceImpl" 
	init-method="myInit" destroy-method="myDestroy"></bean>

<bean class="com.syc.e_lifecycle.MyBeanPostProcessor"></bean>

执行测试类的结果:

3.生成代理对象模拟事务处理

现在又有一个需求,需要在执行目标方法的前后进行事务处理,即在执行目标方法前开启事务,在执行目标方法后提交事务。那么此时需要有一个代理对象,那这个代理对象要写在哪里呢?若写在前处理方法中,因为生成的代理对象就是目标对象,那么当生成的代理对象要执行init()初始化方法时,因为在目标对象的接口中并没有初始化方法所以就会出错,因此需要写在后处理方法中。

我们在后处理方法中进行以下的处理:

@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() {//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;
					}
				});
	}

2.5.4 bean装配基于XML的属性注入

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

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

        基于XML装配:构造方法、setter方法等

        基于注解装配

  • 自动装配:Struts和Spring整合可以自动装配

1.构造方法

目标类:

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;
	}			
				
	@Override
	public String toString() {
		return "User [uid=" + uid + ", username=" + username + ", age=" + age
				+ "]";
	}
	
}

Spring配置:

<!-- 构造方法注入
	* <constructor-arg> 用于配置构造方法一个参数argument
	通过属性名的形式来设置一般是不用的
	<constructor-arg name="username" value="syc"></constructor-arg>
	<constructor-arg name="age" value="11"></constructor-arg>
	
	index:参数的索引号,从零开始,如果只有索引,匹配到了多个构造方法时,默认使用第一个
	type:确定参数类型

 -->
<bean id="userId" class="com.syc.f_xml.a_constructor.User">
	<constructor-arg index="0" type="java.lang.String" value="11"></constructor-arg>
	<constructor-arg index="1" type="java.lang.Integer" value="12"></constructor-arg>
</bean>

测试类:

public class TestCons {
	
	@Test
	public void demo01() throws Exception{
		String xmlPath = "com/syc/f_xml/a_constructor/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		User user = (User) applicationContext.getBean("userId");
		System.out.println(user.toString());
	}
}

2.Setter方法

Setter方法和di类似,下面只给出String的配置文件,另外还有两个类,一个是Person类,定义了姓名,年龄,家庭地址,公司住址;还有一个是地址类,定义了具体地址,和电话。

Spring配置

    <bean id="personId" class="com.syc.f_xml.b_setter.Person">
		<property name="name" value="Jack"></property>
		<property name="age" value="18"></property>
		
		<property name="homeAddr" ref="homeAddrId"></property>
		<property name="companyAddr">
			<ref bean="companyAddrId"/>
		</property>
	</bean>
	
	<bean id="homeAddrId" class="com.syc.f_xml.b_setter.Address">
		<property name="addr" value="浙江"></property>
		<property name="tel" value="119"></property>
	</bean>
	<bean id="companyAddrId" class="com.syc.f_xml.b_setter.Address">
		<property name="addr" value="杭州"></property>
		<property name="tel" value="911"></property>
	</bean>

3.P命名空间(了解)

  • P命名空间是对Setter注入的一种简化,用<bean p:属性名="普通值" p:属性名-ref="引用值"/>替换<property name="属性名" value=""/>
  • P命名空间使用前提,需要加上命名空间:

以上面的Setter方法为例,Spring的配置为:

<bean id="personId" class="com.syc.f_xml.c_p.Person" 
		p:name="Tom" p:age="20" p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
	</bean>
	
	<bean id="homeAddrId" class="com.syc.f_xml.c_p.Address"
		p:addr="江干" p:tel="502">
	</bean>
	<bean id="companyAddrId" class="com.syc.f_xml.c_p.Address"
		p:addr="东京" p:tel="520">
	</bean>

4.SpEL(了解)

SpEL是对<property>进行统一编程,所有的内容都用value="#{ }"来表示

  • #{123}、#{'jack'}  :数字、字符串
  • #{beanId}  :另一个bean引用
  • #{beanId.propName} : 操作数据
  • #{beanId.toString()}  : 执行方法
  • #{T(类).字段|方法} : 静态方法或字段

我们在目标类Customer中定义一个 name,定义一个double类型的pi,Spring的配置如下:

<!-- 
	<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.syc.f_xml.d_spel.Customer">
	<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
	<property name="pi" value="#{T(java.lang.Math).PI}"></property>
</bean>

5.集合注入

集合的形式有:数组, List, Set, Map, Properties等

我们用下面的的几个进行测试,并生成相应的get和set方法,以及toString()方法。

public class CollData {
	private String[] arrayData;
	private List<String> listData;
	private Set<String> setData;
	private Map<String, String> mapData;
	private Properties propsData;
}

Spring的配置:

<!-- 
		集合的注入都是给<property>添加子标签:
		
		数组:<array>
		List:<list>
		Set:<set>
		Map:<map> ,map存放k/v 键值对,使用<entry>描述
		Properties:<props>  <prop key=""></prop> 
		
	 -->
	<bean id="collDataId" class="com.syc.f_xml.e_coll.CollData">
		<property name="arrayData">
			<array>
				<value>Tom</value>
				<value>Bob</value>
			</array>
		</property>
		
		<property name="listData">
			<list>
				<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="Tom" value="汤姆"></entry>
				<entry key="Jack" value="杰克"></entry>
				<entry>
					<key><value>rose</value></key>
					<value>柔丝</value>
				</entry>
			</map>
		</property>
		
		<property name="propsData">
			<props>
				<prop key="1">第一名</prop>
				<prop key="2">第二名</prop>
			</props>
		</property>
	</bean>

测试输出结果:

2.6 装配Bean基于注解(掌握)

注解就是一个类,使用@注解名称

开发中使用注解取代XML配置文件 

2.6.1 使用@Component

更确切的说法是@Component取代<bean class="">,而@Component("实例id")取代<bean id="" class="">

1.添加Schema约束

约束文件位置:spring-framework-3.2.0.RELEASE/docs/spring-framework-reference/html/xsd-config.html

找到2.8的 The context schema,并将其中的加粗语句复制到配置文件中。

将.xsd文件添加到xml catalog中

2.配置

在目标类中添加注解

在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.syc.g_annotaion.a_ioc"></context:component-scan>
	
</beans>

测试文件不变,得到和IoC一样的效果

2.6.2 Web开发的注解

1.Web开发提供了三个 @Component注解的衍生注解(功能一样),都是代替<bean class=""/>

  • @Controller :Web层
  • @Service : Service层
  • @Repository :Dao层

2.依赖注入:给私有字段或者Setter方法设置

普通值:@Vaulue(" ")

引用值:方式1:按照【类型】注入,这里的类型即是接口(适用于一个接口只有一个实现类的情况)

               @Autowired

              方式2:按照【名称】注入1

              @Autowired

              @Qualifier("对象名称")

              方式3:按照【名称】注入2

              @Resource(name="对象名称")

下面用一个具体的例子来演示:

先看测试文件,这里需要获取一个studentAction的对象,通过studentId来获取

public class TestWeb {	
	@Test
	public void demo02(){
		//从Spring容器获得
		String xmlPath = "com/syc/g_annotaion/b_web/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		StudentAction studentAction = (StudentAction) applicationContext.getBean("studentActionId");
		studentAction.execute();
		
	}
}

在Spring配置文件中仍然只需要将组建扫描配置进去就行了

<context:component-scan base-package="com.syc.g_annotaion.b_web"></context:component-scan>

再来看Web层:用@Controller("studentActionId")来声明一个studentAction对象,它依赖于studentService对象,我们用自动注入的方式注入这个对象,因为接口StudentService只有一个实现类,因此可以自动注入。

@Controller("studentActionId")
public class StudentAction {

	@Autowired
	private StudentService studentService;
	
	public void execute() {
		studentService.addStudent();
	}
	
}

用@Service来表示这是一个Service层的对象,在接口中我们只定义了一个addStudent的方法。在Service中,我们需要使用Dao对象,通过方式2-按照【名称】注入,我们给setter方法进行设置(当然也是可以直接给对象设置的)

@Service
public class StudentServiceImpl implements StudentService {
	
	private StudentDao studentDao;
	
	@Autowired
	@Qualifier("studentDaoId")
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

	@Override
	public void addStudent() {
		studentDao.save();
	}

}

最后看Dao层,我们直接用@Repository来声明这个对象以供Service使用。

@Repository("studentDaoId")
public class StduentDaoImpl implements StudentDao {

	@Override
	public void save() {
		System.out.println("Dao");
		
	}
}

运行测试文件的结果就是能够将Dao层的信息输出

2.6.3 生命周期和作用域相关的注解

初始化:@PostConstruct

销毁:@PreDestroy

作用域:@Scope("prototype")

这两个生命周期的注解可以直接写在相应的方法上面(因为在xml文件中,我们是直接配置在bean的 init-method 和 destroy-method方法中的)。下面用一个Service的实现类来举例,当然在我们要使用销毁方法的时候,仍然需要关闭容器applicationContext.close();

@Service("userServiceId")
public class UserServiceImpl implements UserService {

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

}

2.6.4 xml和注解一起使用的情况

xml和注解一起使用,适用于以下的情况:

所有的bean都配置在xml中,所有的依赖都用注解的方式(@Autowired)

此时,默认注解是无法使用的,需要在spring配置文件中添加下面的配置:<context:annotation-config></context:annotation-config>,只需要这个标签体即可。该标签体和<context:component-scan />是无法一起使用的,在有component-scan的时候annotation-config是失效的。

 

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值