配置方式:通过工厂方法配置bean,通过FactoryBean配置bean

配置形式:基于注解的方式

组件扫描

泛型依赖注入

静态工厂方法

 /**
* 静态工厂方法:直接调用某一个类的静态方法就可以返回bean的实例
*/
public class StaticCarFactory {
private static Map<String, Car> cars = new HashMap<String, Car>(); static{
cars.put("audi", new Car("audi",123,123));
cars.put("ford", new Car("ford",123,123));
} public static Car getCar(String name) {
return cars.get(name);
}
}
    <!-- 通过静态工厂方法来配置bean,注意不是配置静态工厂方法实例,而是配置bean实例 -->
<bean id="car1" class="com.text.StaticCarFactory" factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean>

实例工厂方法

 /**
* 实例工厂方法:实例工厂的方法,即先需要创建工厂本身,在调用
* 工厂的实例方法,再配置bean的实例
*/
public class InstanceCarFactory { private Map<String, Car> cars = null; public InstanceCarFactory() {
cars = new HashMap<String, Car>();
cars.put("audi", new Car("audi",123,123));
cars.put("ford", new Car("ford",123,123));
} public Car getCar(String name) {
return cars.get(name);
}
}
     <!-- 配置工厂的实例 -->
<bean id="carFactory" class="com.text.InstanceCarFactory"></bean>
<!-- 通过实例工厂方法来配置bean -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford"></constructor-arg>
</bean>

用FactoryBean配置bean

 //自定义的FactoryBean需要实现提供的接口
public class CarFactoryBean implements FactoryBean<Car> { private String name;
public void setName(String name) {
this.name = name;
} @Override
public Car getObject() throws Exception {
// TODO Auto-generated method stub
return new Car(name,5000,500);
} @Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return Car.class;
} @Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return true;
} }
     <!--
通过FactoryBean来配置bean的实例
class=指向FactoryBean的全类名
property=配置FactoryBean的属性 但实际返回的实例确是FactoryBean的getObject方法返回的实例
-->
<bean id="car" class="com.text.CarFactoryBean">
<property name="name" value="bmw"></property>
</bean>

基于注解的方式配置bean,装配bean的属性

组件扫描:spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件

1. @Component 基本注解

2. @Respository 持久层

3. @Service 业务层

4. @Controller 表现层

可混用,ioc容器分辨不了,不过建议按层使用,value属性可标示beanName

可增加属性resource-pattern指定扫描的资源。如repository/*.class

可增加子节点

<context:exclude-filter type="annotation" expression=""/> 排除
<context:include-filter type="annotation" expression=""/>  包含(在use-default-filters【不使用默认注解】为false时使用)

expression中可填入如org.springframework.stereotype.Repository等包名

    <!-- 指定ioc容器扫描的包 -->
<context:component-scan base-package="com.rep"></context:component-scan>

实例:autowire自动装配具有兼容类型的单个bean属性

@Controller
public class UserController {
@Autowire
private UserService userService; public void controller() {
System.out.println("controller");
userService.add();
}
}
@Service
public class UserService {
public void add() {
System.out.println("add");
}
}

此时,就可以打印

controller
add

写到这里,突然产生了一个疑问,注解形式和xml形式是如何转化的

重新写了相同作用的xml

     <bean id="userController" class="com.rep.UserController" >
<property name="userService" ref="userService"></property>
</bean> <bean id="userService" class="com.rep.UserService"></bean>

在userController中的userService变量需要加上setter方法

运行得出相同结论。然后又产生一个问题,之前为啥用bean来着。。

如果不用bean呢?

     private UserService userService = new UserService();

     public void controller() {
System.out.println("controller");
userService.add();
}
   UserController userController = new UserController();
//(UserController)ctx.getBean("userController");
userController.controller();

写完对比后,就发现:用bean的原因是为了减少耦合,也就是Controller和Service之间不会产生关系,如果不用bean,Controller中需要new一个Service。而在用spring后,所有的bean都交给ioc容器管理,如果你有需要,跟ioc容器getBean即可。

言归正传,autowire可以有一个属性值required,当为false时,即使bean不存在,也不抛异常,而是允许不被设置。

当匹配的bean有两个或多个时,会抛异常expected single matching bean but found 2

解决方法:(以Service为接口,UserService和OtherService作为实现为例

在Controller中定义接口变量service)

1. 在UserService或者OtherService类上添加@Service("service"),value值为接口变量

2. 在autowired下方加入@Qualifier("otherService"),值为所装配的bean

     @Autowired
@Qualifier("otherService")
private Service service;

3. 在参数前加Qualifier,且autowired在setter方法前

     private Service service;
@Autowired
public void setService(@Qualifier("otherService")Service service) {
this.service = service;
}

autowired注解放在

1. 数组类型属性上,spring会把所有匹配的bean进行自动装配

     @Autowired
private Service[] service; public void controller() {
System.out.println("controller");
service[1].add();
}

2. 集合属性上,spring读取该集合的类型信息,然后自动装配所有与之兼容的bean

     @Autowired
private List<Service> service; public void controller() {
System.out.println("controller");
service.get(0).add();
}

3. 在map上,若map的键值为String,spring将自动装配与map值类型兼容的bean,此时bean的名称作为键值

     @Autowired
private Map<String,Service> service; public void controller() {
System.out.println("controller");
service.get("userService").add();
}

泛型依赖注入

public class BaseRepository<T> {

}
@Repository
public class UserRepository extends BaseRepository<User>{ }
public class BaseService<T> {

    @Autowired
protected BaseRepository<T> repository; public void add() {
System.out.println("add");
System.out.println(repository);
}
}
@Service
public class UserService extends BaseService<User>{ }

此时,在main方法中

UserService userService = (UserService)ctx.getBean("userService");
userService.add();

打印结果为

add
com.di.UserRepository@e5a13

即Service父类装配Repository父类,且方法中用的是Repository父类类型变量,当Service子类调用父类方法时,调用的是Repository子类  

spring-bean(三)的更多相关文章

  1. Spring bean三种创建方式

    spring共提供了三种实例化bean的方式:构造器实例化(全类名,反射).工厂方法(静态工厂实例化   动态工厂实例化)和FactoryBean ,下面一一详解: 1.构造器实例化 City.jav ...

  2. 【转】Spring 中三种Bean配置方式比较

    今天被问到Spring中Bean的配置方式,很尴尬,只想到了基于XML的配置方式,其他的一时想不起来了,看来Spring的内容还没有完全梳理清楚,见到一篇不错的文章,就先转过来了. 以前Java框架基 ...

  3. Spring中三种配置Bean的方式

    Spring中三种配置Bean的方式分别是: 基于XML的配置方式 基于注解的配置方式 基于Java类的配置方式 一.基于XML的配置 这个很简单,所以如何使用就略掉. 二.基于注解的配置 Sprin ...

  4. Spring 中三种Bean配置方式比较

    今天被问到Spring中Bean的配置方式,很尴尬,只想到了基于XML的配置方式,其他的一时想不起来了,看来Spring的内容还没有完全梳理清楚,见到一篇不错的文章,就先转过来了. 以前Java框架基 ...

  5. Spring中三个重要概念 IOC AOP Bean

    Spring中三个重要概念 IOC AOP Bean 首先讲解一下Spring框架,以及为什么要使用Spring 框架? spring 是一个很好的容器框架, 是轻量级的IoC和AOP的容器框架,主要 ...

  6. spring Bean配置的三种形式

    Spring Bean配置有以下三种形式: 传统的xml配置 Spring 2.5 以后新增注解配置 Spring3.0以后新增JavaConfig 1. 传统的xml配置 <?xml vers ...

  7. (转)Spring的三种实例化Bean的方式

    http://blog.csdn.net/yerenyuan_pku/article/details/52832793 Spring提供了三种实例化Bean的方式. 使用类构造器实例化. <be ...

  8. spring Bean的三种配置方式

    Spring Bean有三种配置方式: 传统的XML配置方式 基于注解的配置 基于类的Java Config 添加spring的maven repository <dependency> ...

  9. 【Spring IoC】Spring Bean(三)

    一.Spring Bean的定义 被称作 bean 的对象是构成应用程序的支柱也是由 Spring IoC 容器管理的.bean 是一个被实例化,组装,并通过 Spring IoC 容器所管理的对象. ...

  10. Spring(三):bean的自动装配

    Bean的自动装配 自动装配是Spring满足bean依赖的一种方式. Spring会在上下文中自动寻找,并自动给bean装配属性 Spring中三种装配方式 在xml中显式的配置. 在java中显式 ...

随机推荐

  1. HDU4280 Island Transport —— 最大流 ISAP算法

    题目链接:https://vjudge.net/problem/HDU-4280 Island Transport Time Limit: 20000/10000 MS (Java/Others)   ...

  2. Tomcat版本是32位、64位问题

    最近遇到一个Tomcat windows安装版本是32位还是64位问题.由于一系列原因,已经无从知晓生产系统上的该程序是32位还是64位. 后来经过仔细查阅资料,得知: 1. tomcat 从6.0. ...

  3. I.MX6 新版u-boot分析

    /******************************************************************* * I.MX6 新版u-boot分析 * 说明: * 因为一些 ...

  4. 【Codeforces 632D】 Longest Subsequence

    [题目链接] 点击打开链接 [算法] 设取的所有数都是k的约数,则这些数的lcm必然不大于k. 对于[1, m]中的每个数,统计a中有多少个数是它的约数即可. [代码] #include<bit ...

  5. 【Cocos2dx】新建场景、场景的切换、设置启动场景与菜单的新建

    这是Cocos2dx最简单的部分.主要是体现对场景的操作,其实这东西就是Flash的舞台,安卓的Activity,WIN32窗体程序的Framework窗体,网页的body,反正就是对那个容纳各种东西 ...

  6. 022--python 模块介绍和time模块

    一.模块的含义 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代 ...

  7. 如何用GO实现一个tail -f功能以及相应的思维发散

    此文已由作者杨望暑授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 背景 在服务端查看log会经常使用到tail -f命令实时跟踪文件变化. 那么问题来了, 如果自己写一个同样 ...

  8. python iteration 迭代

    可迭代的类型:list,tuple,dict,str,bytes,bytearray等 一.怎么判断一个对象是否可迭代 >>> from collections import Ite ...

  9. git自动化部署+rsync文件同步

    1.进入线上git裸仓库 2.编辑post-receive #!/bin/sh unset GIT_DIR cd /var/www/ git pull http://web:xxxxxxx@120.3 ...

  10. python 标准库大全

    python 标准库 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 string ...