JavaWeb学习-Spring中的Bean使用总结

JavaWeb学习-Spring中的Bean的总结

时间临近期末,写一篇文章用来整理spring中的知识点用于整理思路和复习。


如果把Spring看做一个大型工厂,则Spring容器中的Bean就是该工厂的产品。要想使用这个工厂生产和管理Bean,就需要在配置文件中告诉它需要哪些Bean,以及需要使用何种方式将这些Bean装配到一起。

Bean的本质就是Java中的类,而Spring中的Bean其实就是对实体类的引用,来生产Java类对象,从而实现生产和管理Bean 。

(一)Bean的配置

Spring容器支持两种格式的配置文件

  • Properties文件
  • xml格式文件 :在实际开发中,最常使用的是XML文件格式的配置方式,这种配置方式是通过XML文件来注册并管理Bean之间的依赖关系

首先在com.henu.bean包下定义一个User类

public class User {
	
	private String name;
	private String password;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

在项目的src目录下新建applicationContext.xml文件

<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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 	
 	<bean name="user" class="com.henu.bean.User">
 		<property name="name" value="user1"/>
 		<property name="password" value="123456"/>
 	</bean>
 
</beans>

XML配置文件的根元素是<beans><beans>中包含了多个<bean>子元素,每一个<bean>子元素定义了一个Bean,并描述了该Bean如何被装配到Spring容器中。

其中,name指定此bean的名称(也可以用id),class指定User类的全称,property用来设置类中的属性。

若没有为bean设置nameid,spring会默认用class当做名称使用。

写个测试类来通过xml文件中配置的bean获取User的实例对象。

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			
			System.out.println(user1.getName());
			System.out.println(user1.getPassword());
		}
}

运行,控制台输出我们在property中设置的默认值.

(二)Bean的作用域

spring可以为bean指定他的作用域

  • singleton: spring的默认作用域,单例模式,使用singleton定义作用域的bean在spring容器中将只有一个实例,无论多少个其他的bean引用他,始终指向一个对象。
  • prototype: 原型模式,每次通过getBean方法获取的Bean都是一个新产生的Bean对象。
  • request: 对于每次http请求,使用request作用域的Bean都会产生一个新的实例。
  • session: 对于每此http会话,使用session作用域的Bean都会产生一个新的实例。
  • global session: 每个全局的http会话,都会对应一个Bean实例。相当于全局变量

通过在bean标签设置scope来设置一个bean类的作用域

<bean name="user" class="com.henu.bean.User" scope="singleton">
 		<property name="name" value="user1"/>
 		<property name="password" value="123456"/>
</bean>

我们来打印两个User类的地址

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			User user2 = (User) context.getBean("user");
			System.out.println(user1);
			System.out.println(user2);
		}
}

当作用域为prototype时:

<bean name="user" class="com.henu.bean.User" scope="prototype">
 		<property name="name" value="user1"/>
 		<property name="password" value="123456"/>
 	</bean>

(三) Spring容器中Bean的生命周期

Spring中Bean的生命周期的意义在于,可以利用Bean在其存活期间的特定时刻完成一些相关操作。这种时刻可能有很多,但一般情况下,常会在Bean的postinitiation(初始化后)和predestruction(销毁前)执行一些相关操作。

Spring容器可以管理Bean的部分作用域的生命周期

  • singleton作用域: Spring容器可以管理singleton作用域的Bean的生命周期,在此作用域下,Spring能够精确的知道该Bean何时被创建,何时初始化完成,以及何时被销毁
  • prototype作用域: prototype作用域的Bean,Spring只负责创建,当容器创建了Bean实例后,Bean的实例就交给客户端代码来管理,Spring容器将不再跟踪其生命周期。

Spring容器中的Bean生命周期如下图所示:

(四)Bean的装配方式

创建应用对象之间协作关系的行为通常被称为装配,这也是依赖注入的本质。Spring是一个基于容器的框架。但是如果没有配置Spring,那它就是一个空容器,当然也毫无用处。所以需要配置Spring,以告诉容器需要加载哪些Bean和如何装配这些Bean。

Bean的装配可以理解为依赖关系注入,Bean的装配方式即Bean依赖注入的方式。Spring容器支持多种形式的Bean的装配方式:

  • 基于XML的装配方式
  • 基于注解(Annotation) 常用
  • 自动装配
1.基于XML的装配方式 (Setter注入和构造方法注入)
Setter注入

第一步,在Bean类中必须提供属性的Setter方法

public class User {
	
	private String name;
	private String password;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

第二步,在XML文件中,声明property标签

<bean name="user" class="com.henu.bean.User" >
 		<property name="name" value="user1"/>
 		<property name="password" value="123456"/>
</bean>

property中的name对应属性名,value设置属性的默认值

获取name和password打印

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			
			System.out.println(user1.getName());
			System.out.println(user1.getPassword());
		}
}

构造函数注入

Bean类中必须含有一个有参构造函数

public class User {
	
	private String name;
	private String password;
	
	
	public User(String name, String password) {
		super();
		this.name = name;
		this.password = password;
	}
	
	@Override
	public String toString() {
		
		return this.name+" "+this.password;
	}
	
}

xml中修改:

<bean name="user" class="com.henu.bean.User" >
 		<constructor-arg index="0" value="user1"/>
 		<constructor-arg index="1" value="password"/>
</bean>

通过constructor-arg标签来为每个构造函数的参数赋值,index表示参数的顺序。

打印一下user

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			
			System.out.println(user1.toString());
			
		}
}

2. 基于注解(Annotation)的装配方式

基于XML的装配可能会导致XML配置文件过于臃肿,给后续的维护和升级带来一定的困难。为此,Spring提供了对Annotation(注解)技术的全面支持.

新建一个Phone类 ,并在applicationContext.xml中添加Bean。

public class Phone {
	
	public void call() {
		System.out.println("is calling...");
	}
	
}

当一个类作为成员变量被另一个类持有时 ,若用基于xml的装配方式需要使用property标签 并用ref指定phone类的bean的name.

package com.henu.bean;

public class User {
	
	private String name;
	private String password;
	
	private Phone phone;

	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Phone getPhone() {
		return phone;
	}

	public void setPhone(Phone phone) {
		this.phone = phone;
	}
	
}

applicationContext.xml

<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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 	
 	
 	<bean name="phone" class="com.henu.bean.phone"/>
 	
 	<bean name="user" class="com.henu.bean.User" >
 		<property name="name" value="user1..."/>
 		<property name="password" value="123456"/>
 		<property name="phone" ref="phone"/>
 	</bean>
 
</beans>

测试一下

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			
			user1.getPhone().call();
			
		}
}

spring容器会自动根据在xml中配置的bean将之实例化,我们只需要即拿即用。

但是如果类中的属性过多,就会造成xml文件的臃肿,不好管理。这时我们可以使用注解的方式 。

@Autowired注解

在xml文件中删除user中的phone的property标签,添加<context:annotation-config/>

 	<context:annotation-config />
 	<bean name="phone" class="com.henu.bean.Phone"/>
 	
 	<bean name="user" class="com.henu.bean.User" >
 		<property name="name" value="user1..."/>
 		<property name="password" value="123456"/>
 	</bean>

在User类中,对属性phone成员变量进行注解

public class User {
	
	private String name;
	private String password;
	
	@Autowired
	private Phone phone;

	
	...

}

不修改测试类直接运行,能够正确输出。

@Resource(name=" ")注解
public class User {
	
	private String name;
	private String password;
	
	@Resource(name="phone")
	private Phone phone;

	
	...

}

通过@Resource注解同样能达到效果,name指定xml中Phone类的name

@Component注解

如果我们的bean过多,同样也会造成xml文件的臃肿,spring提供了@Component注解,通过@Component注解可以直接省去在xml中配置bean的麻烦。

首先删除掉applicationContext.xml中的bean

添加<context:component-scan base-package="com.how2java.pojo"/>

<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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 	
 	<context:component-scan base-package="com.henu.bean"/>
 
</beans>

base-package中写入我们bean所在的包名

然后使用@Component注解User,Phone类

@Component
public class Phone {
	
	public void call() {
		System.out.println("is calling...");
	}
	
}
@Component
public class User {
	
	private String name;
	private String password;
	
	@Resource(name="phone")
	private Phone phone;

	
	...
	
}

不修改测试类,运行

public class TestBean {

	
		public static void main(String[] args) {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					new String[] {"applicationContext.xml"});
			
			User user1 = (User) context.getBean("user");
			
			user1.getPhone().call();
			
		}
}

成功输出与之前一样的效果

@Scope作用域注解
@Component
@Scope("singleton")
public class User {
	
	private String name;
	private String password;
	
	@Resource(name="phone")
	private Phone phone;
    
    ...
}

通过@Scope注解作用域,与xml配置一样的效果

关于spring中Bean的知识点整理到此结束,希望能在期末考一个好成绩吧↖(ω)↗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值