最近又买了一本介绍SSM框架的书,是由黑马程序员编写的,书上讲的很好理解,边看边总结一下。主要总结一下bean的装配方式。

Bean的装配可以理解为依赖系统注入,Bean的装配方式即Bean依赖注入的方式。Spring容器支持多种形式的Bean装配方式,如基于XML的装配、基于注解(Annotation)的装配方式和自动装配等(其中最常用的是基于注解的装配)。

基于xml的装配

Spring 提供了两种基于xml的装配方式:设值注入(Setter Injection)和构造注入(Constructor Injection)。

在Spring实例化Bean的过程中,Spring 首先会调用Bean的默认构造方法来实例化Bean对象,然后通过反射的方式调用setter方法来注入属性值。因此,设值注入要求一个Bean必须满足两点要求

  • Bean类必须提供一个默认的无参的构造方法
  • Bean类必须为需要注入的属性提供对应的setter方法

案例:

新建一个User实体类,包含三个属性username,password,list

import java.util.List;

public class User {
private String username;
private Integer password;
private List<String> list; public User(String username, Integer password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
} public User() {
super();
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
} @Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", list=" + list + "]";
} }

一个xml的配置文件beans.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-4.3.xsd"> <!-- 使用构造器注入方式装配user实例 -->
<bean id="user1" class="com.itheima.assemble.User">
<constructor-arg index="0" value="tom" />
<constructor-arg index="1" value="123456" />
<constructor-arg index="2">
<list>
<value>"constructorvalue1"</value>
<value>"constructorvalue2"</value>
</list>
</constructor-arg>
</bean> <!-- 使用设值注入方式装配User实例 -->
<bean id="user2" class="com.itheima.assemble.User">
<property name="username" value="张三"></property>
<property name="password" value="654321"></property>
<property name="list">
<list>
<value>"setlistvalue1"</value>
<value>"setlistvalue2"</value>
</list>
</property>
</bean> </beans>

测试类

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class XmlBeanAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/assemble/beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); System.out.println(applicationContext.getBean("user1"));
System.out.println(applicationContext.getBean("user2")); }
}

控制台信息如下:

基于Annotation的装配

Spring中定义了一系列的注解,常用的注解如下所示:

  • @Component: 可以使用此注解描述Spring中的Bean,但它是一个泛化的概念,仅仅表示一个组件,并且可以作用于任何层次。

  • @Repository: 用于将数据访问层(DAO层)的类标识为Spring中的Bean,功能和Component注解相同。

  • @Service: 通过作用于业务层(Service层),用于将业务层的类标识为Spring中的Bean,功能和Component注解相同。

  • @Controller: 通常作用于控制层(如Spring mvc中的Controller),用于将控制层的类标识为Spring 中的Bean,功能和Component注解相同。

  • @Autowired: 用于对Bean的属性变量、属性的 setter 方法及构造方法进行标注,配合对应的注解处理器完成Bean的自动配置工作。默认按照Bean的类型进行装配。

  • @Resource: 其作用与Autowired一样。区别在于 @Autowired 默认按照Bean类型装配,而 @Resource 默认按照Bean实例名称进行装配。

    @Resource有两个重要属性:name和type。Spring将name属性解析为Bean实例名称,type解析为Bean的实例类型。

    如果指定 name 属性,则按实例名称进行装配;如果指定 type 属性,则按Bean类型进行装配;

    如果都不指定,则先按Bean实例名称装配,如果不能匹配,再按照Bean类型进行装配;如果都无法匹配,则抛出NoSuchBeanDefinitionException异常。

  • @Qualifier: 与 @Autowired 注解配合使用,会将默认的按Bean类型装配修改为按Bean的实例名称装配,Bean的实例名称由 @Qualifier 注解参数指定。

下面通过案例,学习使用这些注解:

1.新建一个接口,并定义方法:


public interface UserDao {
public void save();
}

2.建立UserDao的实现类,UserDaoImpl并实现接口中的方法:

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImpl implements UserDao{ @Override
public void save() {
System.out.println("userDao......save....");
} }

3.新建UserService接口,定义save()方法:


public interface UserService {
public void save();
}

4.创建UserService接口的实现类UserServiceImpl,实现接口中的save()方法:


import javax.annotation.Resource; import org.springframework.stereotype.Service; @Service("userService")
public class UserServiceImpl implements UserService{
@Resource(name="userDao")
private UserDao userDao;
@Override
public void save() {
this.userDao.save();
System.out.println("userservice...save...");
} }

5.创建控制器类UserController


import javax.annotation.Resource; import org.springframework.stereotype.Controller; @Controller("userController")
public class UserController {
@Resource(name="userService")
private UserService userService;
public void save(){
this.userService.save();
System.out.println("userController...save...");
}
}

6.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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 使用context命名空间,在配置文件中开启相应的注解处理器 -->
<context:annotation-config/>
<!-- 使用 context 命名空间,通知 Spring 扫描指定包下所有Bean类,进行注解解析。如果不用这种方式,可以像下面注释的一样,分别定义3个Bean实例 -->
<context:component-scan base-package="com.itheima.annotation"/> <!-- <bean id="userDao" class="com.itheima.annotation.UserDaoImpl"/>
<bean id="userService" class="com.itheima.annotation.UserServiceImpl"/>
<bean id="userController" class="com.itheima.annotation.UserController"/> --> </beans>

7.编写测试类AnnotationAssembleTest:


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationAssembleTest {
public static void main(String[] args) {
//定义配置文件路径
String xmlPath = "com/itheima/annotation/beans6.xml";
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获取UserController实例
UserController userController = (UserController) applicationContext.getBean("userController");
//调用save()方法
userController.save();
}
}

运行结果如图:

小结

@Repository等注解其实相当于在配置文件中<bean id="userDao" class="com.itheima.annotation.UserDaoImpl"/>的编写。

上述案例需要的包有:

Spring 中Bean的装配方式的更多相关文章

  1. Spring中Bean的装配方式

    一.基于xml的装配 Student.java package com.yh; public class Student implements People { public void breath( ...

  2. java开发两年,连Spring中bean的装配都不知道?你怎么涨薪啊

    Spring 1.1.1.1 创建一个bean package com.zt.spring; public class MyBean { private String userName; privat ...

  3. Spring中bean的注入方式

    首先,要学习Spring中的Bean的注入方式,就要先了解什么是依赖注入.依赖注入是指:让调用类对某一接口的实现类的实现类的依赖关系由第三方注入,以此来消除调用类对某一接口实现类的依赖. Spring ...

  4. Spring笔记2——Spring中Bean的装配

    1.引言 Spring中,对象无需自己负责查找或创建与其关联的其他对象,而是由容器负责把需要相互协作的对象引用赋予各个对象.创建应用对象之间的协作关系的行为通常称为装配(Wiring),这也是依赖注入 ...

  5. spring中 Bean的装配 Bean后处理器

  6. 【Spring】Spring中的Bean - 5、Bean的装配方式(XML、注解(Annotation)、自动装配)

    Bean的装配方式 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 文章目录 Bean的装配方式 基于XML的装配 基于注解 ...

  7. Spring Bean 的装配方式

    Spring Bean 的装配方式 装配 Bean 的三种方式 一个程序中,许多功能模块都是由多个为了实现相同业务而相互协作的组件构成的.而代码之间的相互联系又势必会带来耦合.耦合是个具有两面性的概念 ...

  8. spring中bean实例化时机以及整个运转方式

    接上一篇文章,一般在servlet获取到请求之后 在service方法中就可以完成所有的请求处理以及返回,但是我们会采用更高级的MVC框架来做.也就是说所有的MVC框架入口就是serlvet中的ser ...

  9. Spring中Bean的实例化

                                    Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...

随机推荐

  1. 网络协议之DHCP与Route20170330

    由于要使用网络通讯,所以不可避免的要用到dhcp.理想的网络通讯方式是下面3种都要支持: 1,接入已有网络.这便要求可以作为dhcp客户端. 2,作为DHCP服务器,动态分配IP. 3,指定固定IP ...

  2. 一些常见算法的JavaScript实现

    在Web开发中,JavaScript很重要,算法也很重要.下面整理了一下一些常见的算法在JavaScript下的实现,包括二分法.求字符串长度.数组去重.插入排序.选择排序.希尔排序.快速排序.冒泡法 ...

  3. Codeforces 931.F Teodor is not a liar!

    F. Teodor is not a liar! time limit per test 1 second memory limit per test 256 megabytes input stan ...

  4. vue使用插件 使用库

    用插件1.引用import VueResource from 'vue-resource'2.使用Vue.use(VueResource); 用库(bootstrap alertify )1.引入: ...

  5. oracle,sqlserver,mysql常见数据库jdbc连接

    发现JDBC连接字符串总是容易忘记,特此整理一下常用的几种数据的连接 ORACLE: /** * ORACLE * */ public static Connection getOracleConne ...

  6. 跟我一起写Makefile(七)

    make 的运行—————— 一般来说,最简单的就是直接在命令行下输入make命令,make命令会找当前目录的makefile来执行,一切都是自动的.但也有时你也许只想让make重编译某些文件,而不是 ...

  7. [洛谷P2745] [USACO5.3]窗体面积Window Area

    洛谷题目链接:[USACO5.3]窗体面积Window Area 题目描述 你刚刚接手一项窗体界面工程.窗体界面还算简单,而且幸运的是,你不必显示实际的窗体.有 5 种基本操作: 创建一个新窗体 将窗 ...

  8. elasticsearch ik中文分词器的安装配置使用

    安装步骤  https://github.com/medcl/elasticsearch-analysis-ik 以插件形式安装: [elsearch@localhost elasticsearch- ...

  9. php输出日志的实现

    php输出日志的实现 思想:在想要输出log日志的地方,使用php的写入文件函数,把数据写入到事先定义好的文件中. php代码如下: //输出日志 public function outputLog( ...

  10. TED_Topic2:My desperate journey with a human smuggler

    My desperate journey with a human smuggler By Barat Ali Batoor When I was a child there was a toy wh ...