最近又买了一本介绍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. Java试题二

    QUESTION 37Given:1. class Super {2. private int a;3. protected Super(int a) { this.a = a; }4. } ...1 ...

  2. LeakCanary原理分析

    参考文档 http://blog.csdn.net/wyfei021/article/details/46506521http://vjson.com/wordpress/leakcanary%e6% ...

  3. eclipse插件大全(官方)

    eclipse插件大全:http://marketplace.eclipse.org/metrics/successful_installs 各个版本插件: http://download.eclip ...

  4. php 傻瓜式代码计算两个时间间隔

    $stamp = (strtotime($_POST['start'])-strtotime($_POST['end'])); $s = $stamp%60; //秒 $m_stamp= ($stam ...

  5. dva 笔记

    最简单的结构 // 创建应用 const app = dva(); // 注册 Model app.model({ namespace: 'count', state: 0, reducers: { ...

  6. 2017北京国庆刷题Day7 afternoon

    期望得分:100+30+100=230 实际得分:60+30+100=190 排序去重 固定右端点,左端点单调不减 考场上用了二分,没去重,60 #include<cstdio> #inc ...

  7. PhotoSwipe 图片浏览插件使用方法

    一.简介 PhotoSwipe 是专为移动触摸设备设计的相册/画廊.兼容所有iPhone.iPad.黑莓6+,以及桌面浏览器.底层实现基于HTML/CSS/JavaScript,是一款免费开源的相册产 ...

  8. 20155117王震宇 2016-2017-2 《Java程序设计》第九周学习总结

    教材学习内容总结 JDBC JDBC API是一个Java API,可以访问任何类型表列数据,特别是存储在关系数据库中的数据.JDBC代表Java数据库连接. JDBC库中所包含的API任务通常与数据 ...

  9. JavaScript数据类型和转换

    JavaScript数据类型 1.Boolean(布尔) 布尔:(值类型)var b1=true;//布尔类型 2.Number(数字) 数值:(值类型)var n1=3.1415926;//数值类型 ...

  10. 大数mod的技巧

    1.mod 3 将各个位上的数字相加对3求余. 2.mod 11 设这个数为abcdefghijklmnopqrst. ans=(t-s+r-q+p-o+n-m+l-k+j-i(以此类推))mod 1 ...