Spring学习笔记--Spring-认识Bean

继续前一篇
这篇是我感觉最重要的一篇,对我学习Spring Boot有很大启发。。所以我单独分开了。
那就来学习一下Bean的装配方式吧!

Bean的装配方式

1. 基于XML的配置

Spring提供了两种基于XML的装配方式:设值注入,构造注入

  • 设值注入

    • 原理:Spring首先会调用Bean的默认构造方法来实例化Bean对象,然后通过反射的方式调用setter方法来注入属性值。
    • 要求:
      1. Bean类必须提供一个默认的无参构造方法。
      2. Bean类必须为需要注入的属性提供对应的setter方法。
      3. 需要使用<Bean>的子元素<property>来为每个属性注入值(前一篇介绍)
    • 例子:
      1. 创建一个Web项目,导入所需jar包(所需jar包已讲过),在src中创建包(我创建包名com.xhh.assemble)
      2. 在包中创建类(我创建类Student),在该类中定义id(String),name(String),list(集合)三个属性及其对应的setter方法(有参数的构造函数为构造注入所用),如下 Student.java类。
      3. 创建配置文件xml(我创建的Student.xml)利用 <Bean>的子元素<property>设值,在前一篇已讲到。如下Student.xml
      4. 创建测试类,StudentTest.java
  • 构造注入

    • 原理:Spring首先会调用Bean的默认构造方法来实例化Bean对象,然后通过反射的方式调用setter方法来注入属性值。
    • 要求:
      1. Bean类必须提供一个有参构造方法。(参数为需要的属性)
      2. 需要使用<Bean>的子元素constructor-arg来为每个属性注入值(前一篇介绍)
    • 例子:
      1. 在设值注入的基础上(Student.java)中添加相应构造函数
      2. 创建配置文件xml(我创建的Student.xml)利用 <Bean>的子元素constructor-arg设值,在前一篇已讲到。如下Student.xml
      3. 创建测试类,StudentTest.java

Student.java

package com.xhh.assemble;

import java.util.List;

public class Student {

	
	public String id;
	public String name;
	public List<String> list;
	
	/**
	 *	构造注入 
	 */
	public Student(String id, String name, List<String> list) {
		this.id = id;
		this.name = name;
		this.list = list;
	}
	
	/**
	 * 设值注入
	 */
	public Student() {
	}
	
	public void setId(String id) {
		this.id = id;
	}

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

	public void setList(List<String> list) {
		this.list = list;
	}
	
	// 方便看结果
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", list=" + list + "]";
	}

	
}

Student.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="student2" class="com.xhh.assemble.Student">
		<property name="id" value="1002"></property>
		<property name="name" value="李四"></property>
		<property name="list">
			<list>
				<value>"PHP"</value>
				<value>"IOS"</value>
			</list>
		</property>
		
	</bean>

	<!-- 构造注入 -->
    <bean id="student1" class="com.xhh.assemble.Student">
    	<constructor-arg index="0" value="1001"></constructor-arg>
    	<constructor-arg index="1" value="张三"></constructor-arg>
    	<constructor-arg index="2">
    		<list>
    			<value>"java"</value>
    			<value>"Android"</value>
    		</list>
    	</constructor-arg>
    </bean>

	
</beans>

StudentTest.java

package com.xhh.assemble;

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


public class StudentTest {

	public static void main(String[] args) {
		ApplicationContext context = new 
				ClassPathXmlApplicationContext("com/xhh/assemble/Student.xml");
		
		// 构造注入
		Student student1 = (Student) context.getBean("student1");
		System.out.println(student1.toString());
		
		// 设置注入
		Student student2 = (Student) context.getBean("student2");
		System.out.println(student2.toString());
	}
}

*2. 基于Annotation(注解)的配置

尽管使用XML配置文件可以实现Bean的装配工作,但如果应用中有很多Bean,会导致XML配置文件过于臃肿,后续维护/升级带来一定的困难。因此,Spring提供了Annotation(注解)技术的全面支持。

常用注解如下:

注解描述
@Component此注解描述Spring中的Bean,可作用于任何层次(仅仅表示一个Bean)
@Respository用于数据访问层(Dao层或者叫Mapper层)的类标识Spring中的Bean
@Service用于将业务层(Service层)的类标识为Spring中的Bean
@Controller用于将控制层(如Spring MVC中的Controller) 的类标识为Spring中的Bean
@Autowired用于对Bean的属性变量,属性的setter方法及构造方法进行标注(按照Bean的类型装配)
@Resource与Autowired类似,但按照Bean的实例名称装配 (它有两个重要属性name,type)
@Qualifier与@Autowired配合使用,会将按Bean类型装配修改为按实例名称装配

虽然@Respository,@Service,@Controller功能与@Component功能相同,但为了使标注类本身用途更加清晰,建议使用@Respository,@Service,@Controller分别对类进行标注。

演示如何通过注解来装配Bean

  • 在Src目录下,创建包(我创建com.xhh.annotation),在包中创建接口

StudentDao.java

package com.xhh.annotation;

public interface StudentDao {
	public void writer();
}

  • 创建接口的实现类,在类中使用@Repository(“studentDao”)注解将StudentDaoImpl.java标识为Spring中的Bean。写法相当于
    • <bean id="studentDao" class="com.xhh.annotation.StudentDaoImpl"></bean>

StudentDaoImpl.java

package com.xhh.annotation;

import org.springframework.stereotype.Repository;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {

	@Override
	public void writer() {
		// 用于验证是否成功调用了该方法
		System.out.println("StudentDaoImpl:学生信息写入成功。。。");
	}

}

  • 在包中创建接口

StudentService.java

package com.xhh.annotation;

public interface StudentService {

	public void register();
}

  • 创建StudentService.java接口的实现类StudentServiceImpl.java,首先使用@Service(“studentService”)注解将StudentServiceImpl.java类标识为Spring中的Bean,这相当于
    • <bean id="studentService" class="com.xhh.annotation.StudentServiceImpl"></bean>,然后使用@Resource(name = “studentDao”)注解标注在属性studentDao上,这相当于<property name="studentDao" ref="studentDao"></property>

StudentServiceImpl.java

package com.xhh.annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

	@Resource(name = "studentDao")
	private StudentDao studentDao;
	
	@Override
	public void register() {
		// 用于验证是否成功调用了该方法
		this.studentDao.writer();
		System.out.println("StudentServiceImpl:学习信息注册成功。。。");
	}

}

  • 在包中创建控制器类StudentController.java,首先用@Controller(“stuController”)注解标注了该类,这相当于在配置文件中编写
    • <bean id="stuController" class="com.xhh.annotation.StudentController"></bean>,然后使用@Resource(name = “studentService”)注解标注在属性studentService上,这相当于<property name="studentService" ref="studentService"></property>

StudentController.java

package com.xhh.annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

@Controller("stuController")
public class StudentController {

	@Resource(name = "studentService")
	private StudentService studentService;
	
	public void save() {
		// 用于验证是否成功调用了该方法
		this.studentService.register();
		System.out.println("StudentController:学生信息已保存");
	}
}

  • 创建配置文件XML(Student.xml)

Student.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:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	  <!-- 使用context命名空间,在配置文件中开启注解处理器 -->
	  <context:annotation-config />
	  <!-- 分别定义3个bean -->
	  <bean id="studentDao" class="com.xhh.annotation.StudentDaoImpl"></bean>
	  <bean id="studentService" class="com.xhh.annotation.StudentServiceImpl"></bean>
	  <bean id="stuController" class="com.xhh.annotation.StudentController"></bean>
	
</beans>
  • 创建测试类

AnnotationTest.java

package com.xhh.annotation;

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


public class AnnotationTest {

	public static void main(String[] args) {
		ApplicationContext context = new 
				ClassPathXmlApplicationContext("com/xhh/annotation/student.xml");
		
		StudentController stuController = (StudentController) context.getBean("stuController");
		stuController.save();
	}
}

运行后报错!!

在这里插入图片描述

原因:如果使用Spring4.0以上的版本对指定包中的注解进行扫描前,需要先向项目中导入Spring AOP的jar包spring-aop-4.3.6.RELEASE.jar,否则会报错java.lang.NoClassDefFoundError。

导入后运行成功!!
在这里插入图片描述
上述XML配置文件虽然很大程度简化了Bean的配置,但还需要配置相应的Bean

可以使用
<context:component-scan base-package="com.xhh.annotation" />
替代

<?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-4.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	  <!-- 使用context命名空间,在配置文件中开启注解处理器 -->
<!-- 	  <context:annotation-config /> -->
	  <!-- 分别定义3个bean -->
<!-- 	  <bean id="studentDao" class="com.xhh.annotation.StudentDaoImpl"></bean> -->
<!-- 	  <bean id="studentService" class="com.xhh.annotation.StudentServiceImpl"></bean> -->
<!-- 	  <bean id="stuController" class="com.xhh.annotation.StudentController"></bean> -->
	  
	  <context:component-scan base-package="com.xhh.annotation" />
</beans>

完成。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值