1.通过工厂方法配置bean

beans-factory.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过静态工厂方法配置 bean 注意 不是配置静态工厂方法实例, 而是配置bean实例 -->
<!-- class 属性指向 静态工厂方法的全类名
factory-method :指向静态工厂方法的名字
constructor-args:如果工厂方法需要传入参数, 则使用constructor-args 类配参数 -->
<bean id="car1" class="com.aff.spring.beans.factory.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean> <!-- 配置工厂的实例 -->
<bean id="carFactory" class="com.aff.spring.beans.factory.InstanceCarFactory"></bean> <!--通过实例工厂方法来配置bean -->
<!-- class 属性指向 实例工厂方法的全类名
factory-bean:指向实例工厂方法的名字
factory-method :指向实例工厂方法的名字
constructor-args:如果工厂方法需要传入参数, 则使用constructor-args 类配参数 -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean>
</beans>

Main

package com.aff.spring.beans.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
Car car1 = (Car) ctx.getBean("car1");
System.out.println(car1);
// Car [brand=audi, price=20000.0] Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
//Car [brand=audi, price=309000.0] } }

①通过调用静态工厂方法创建 Bean

  调用静态工厂方法创建 Bean是将对象创建的过程封装到静态方法中. 当客户端需要对象时, 只需要简单地调用静态方法, 而不同关心创建对象的细节.

  要声明通过静态方法创建的 Bean, 需要在 Bean 的 class 属性里指定拥有该工厂的方法的类, 同时在 factory-method 属性里指定工厂方法的名称.

最后, 使用 <constrctor-arg> 元素为该方法传递方法参数.

StaticCarFactory.java

package com.aff.spring.beans.factory;

import java.util.HashMap;
import java.util.Map; //静态工厂犯法: 直接 调用一个类的静态方法就可以返回一个bean的实例
public class StaticCarFactory { private static Map<String, Car> cars = new HashMap<String, Car>(); static {
cars.put("audi", new Car("audi", 20000));
cars.put("ford", new Car("ford", 300000));
} // 静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
} }

②通过调用实例工厂方法创建 Bean

实例工厂方法: 将对象的创建过程封装到另外一个对象实例的方法里. 当客户端需要请求对象时, 只需要简单的调用该实例方法而不需要关心对象的创建细节.
要声明通过实例工厂方法创建的 Bean
        在 bean 的 factory-bean 属性里指定拥有该工厂方法的 Bean
        在 factory-method 属性里指定该工厂方法的名称
        使用 construtor-arg 元素为工厂方法传递方法参数

InstanceCarFactory.java

package com.aff.spring.beans.factory;

import java.util.HashMap;
import java.util.Map; //实例工厂方法实例工厂的方法, 即需要创建工厂本身, 在调用 工厂的实例方法来返回bean 的实例
public class InstanceCarFactory {
private Map<String, Car> cars = null; public InstanceCarFactory() {
cars = new HashMap<String, Car>();
cars.put("audi", new Car("audi", 309000));
cars.put("ford", new Car("ford", 2823309));
} public Car getCar(String brand) {
return cars.get(brand);
} }

Car

package com.aff.spring.beans.factory;

public class Car {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return
price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
public Car() {
System.out.println("car 的无参构造器");
}
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
} }

2. 通过FactoryBean 配置bean的实例

CarFactoryBean.java

package com.aff.spring.beans.factorybean;

import org.springframework.beans.factory.FactoryBean;

//自定义FactoryBean 需要实现FactoryBean  接口
public class CarFactoryBean implements FactoryBean<Car> {
private String brand; public void setBrand(String brand) {
this.brand = brand;
} // 返回bean 的对象
@Override
public Car getObject() throws Exception {
return new Car("ford", 320000);
} /**
* 返回 bean 的类型
*/
@Override
public Class<?> getObjectType() {
return Car.class;
} @Override
public boolean isSingleton() {
return true;
} }

beans-factorybean.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过FactoryBean 配置bean的实例
class指向FactoryBean 的全类名
property :配置FactoryBean 的属性
但实际返回的实例却是 FactoryBean 的getObject()方法 返回的实例
-->
<bean id="car" class="com.aff.spring.beans.factorybean.CarFactoryBean">
<property name="brand" value="audi"></property>
</bean>
</beans>

Main

package com.aff.spring.beans.factorybean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factorybean.xml"); Car car = (Car) ctx.getBean("car");
System.out.println(car);
//Car [brand=ford, price=320000.0] } }

3.通过注解配置bean

@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件

当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan> :
base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.
当需要扫描多个包时, 可以使用逗号分隔.

@Autowired 注解自动装配具有兼容类型的单个 Bean属性

构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解

默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常,

若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false

默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作.

此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称
@Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.
@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.
@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值

目录

beans-annotation.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--指定Spring IOC容器扫描的包 -->
<context:component-scan base-package="com.aff.spring.beans.annotation"></context:component-scan>
<!--可以通过 resource-pattern 指定扫描的资源 -->
<!-- <context:component-scan base-package="com.aff.spring.beans.annotation"
resource-pattern="repository/*.class"></context:component-scan> --> <!--context:exclude-filter 子节点指定排除那些指定表达式的组件 -->
<!-- <context:component-scan base-package="com.aff.spring.beans.annotation"
use-default-filters="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
context:include-filter:只包含它,其他的不行 需要默认的过滤器设置为false
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
--> <!-- <context:component-scan base-package="com.aff.spring.beans.annotation">
assignable 不包含这个接口以及这个接口的所有实现类了
<context:include-filter type="assignable"
expression="com.aff.spring.beans.annotation.repository.UserRepository" />
</context:component-scan> <context:component-scan base-package="com.aff.spring.beans.annotation" use-default-filters="false">
assignable 只包含这个接口以及这个接口的所有实现类了
<context:include-filter type="assignable"
expression="com.aff.spring.beans.annotation.repository.UserRepository" />
</context:component-scan>
-->
</beans>

Main

package com.aff.spring.beans.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.aff.spring.beans.annotation.controller.UserContorller;
import com.aff.spring.beans.annotation.repository.UserRepository;
import com.aff.spring.beans.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
//
// TestObject to = (TestObject) ctx.getBean("testObject");
// System.out.println(to); UserContorller userContorller = (UserContorller) ctx.getBean("userContorller");
System.out.println(userContorller);
userContorller.execute();
/* com.aff.spring.beans.annotation.controller.UserContorller@36b4cef0
UseController execute...
UserService add...
UserRepository Save...*/ // UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
// System.out.println(userRepository);
//
// UserService userService = (UserService) ctx.getBean("userService");
// System.out.println(userService);
//
} // com.aff.spring.beans.annotation.TestObject@467aecef
// com.aff.spring.beans.annotation.controller.UserContorller@4d50efb8
// com.aff.spring.beans.annotation.repository.UserRepositoryImlp@7e2d773b
// com.aff.spring.beans.annotation.service.UserService@2173f6d9
}

TestObject.java

@Component
public class TestObject { }

UserContorller.java

@Controller
public class UserContorller {
@Autowired
private UserService userService ;
public void execute(){
System.out.println("UseController execute...");
userService.add();
} }

UserRepository.java

public interface UserRepository {

    void save();
}

UserRepositoryImlp.java

package com.aff.spring.beans.annotation.repository;

import org.springframework.stereotype.Repository;
//实现类 持久化层 repository //@Repository("userRepository")
@Repository
public class UserRepositoryImlp implements UserRepository{ @Override
public void save() {
System.out.println("UserRepository Save..."); } }

UserService.java

package com.aff.spring.beans.annotation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service; import com.aff.spring.beans.annotation.repository.UserRepository; @Service
public class UserService {
private UserRepository userRepository; //在进行装配的时候使用 userRepositoryImlp, 可以放到里面去
@Autowired
public void setUserRepository(@Qualifier("userRepositoryImlp") UserRepository userRepository) {
this.userRepository = userRepository;
} public void add() {
System.out.println("UserService add...");
userRepository.save();
} }

UserJdbcRepository.java

package com.aff.spring.beans.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository
public class UserJdbcRepository implements UserRepository{ @Override
public void save() {
System.out.println("UserJdbcRepository save...");
} }

整个目录

Spring_Bean的配置方式的更多相关文章

  1. Hibernate配置方式

    Hibernate配置方式 Hibernate给人的感受是灵活的,要达到同一个目的,我们可以使用几种不同的办法.就拿Hibernate配置来说,常用的有如下三种方式,任选其一. 在 hibernate ...

  2. ASP.NET 操作Excel中的DCOM配置方式

    具体配置方式如下: 1. 组件服务管理窗口 在运行栏中输入命令:dcomcnfg,打开组件服务管理窗口,在组件服务->计算机->我的电脑->DCom配置->找到Microsof ...

  3. ETL利器Kettle实战应用解析系列三 【ETL后台进程执行配置方式】

    本文主要阅读目录如下: 1.简介Kettle的Kitchen和Span 2.命令行调度任务配置方式 3.后台进程配置运行方式 4.Windows任务设置 5.Demo下载 1.简介Kettle的Kit ...

  4. c3p0三种配置方式(automaticTestTable)

    c3p0的配置方式分为三种,分别是http://my.oschina.net/lyzg/blog/551331.setters一个个地设置各个配置项2.类路径下提供一个c3p0.properties文 ...

  5. 【Spring3.0系列】---Bean不同配置方式比较 和适用场合

    Bean不同配置方式比较1.基于XML配置定义:在XML文件中通过<bean>元素定义Bean,例如<bean class="com.bbt.UserDao"/& ...

  6. struts_20_对Action中所有方法、某一个方法进行输入校验(基于XML配置方式实现输入校验)

    第01步:导包 第02步:配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app ...

  7. struts2视频学习笔记 22-23(基于XML配置方式实现对action的所有方法及部分方法进行校验)

    课时22 基于XML配置方式实现对action的所有方法进行校验   使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类 ...

  8. Spring注解和配置方式

    Spring提供了一个org.springframework.beans.factory.FactoryBean工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑. 从Spring3.0开始, ...

  9. spring AOP advice 类型 和 通用的切点的配置方式

    spring aop advice的类型: 1.前置通知(before advice) 2.返回后通知(after returning advice) 3.抛出异常后通知(after throwing ...

随机推荐

  1. Jmeter-接口测试参数化后循环断言不同内容的方法

    前言 各位小伙伴在做接口自动化有没遇到过这样的问题,CSV文件参数化测试数据后,只能通过人工的的方法去查看结果,不懂写代码去循环断言返回的结果.今天我们来学习一下,不用写代码,就用响应断言,怎么实现循 ...

  2. css的属性选择器

    语法说明: 属性选择器需要将对应属性放入到 方括号中  [ ] ,其中包含属性名,标识符(* $ ~ ^ |) 使用说明: [attribute] 例如  [target] 表示 选择带有 targe ...

  3. 微信小程序使用GoEasy实现websocket实时通讯

    不需要下载安装,便可以在微信好友.微信群之间快速的转发,用户只需要扫码或者在微信里点击,就可以立即运行,有着近似APP的用户体验,使得微信小程序成为全民热爱的好东西~ 同时因为微信小程序使用的是Jav ...

  4. CF-448C Painting Fence 分治

    Painting fence 题意 乍一看以为是之前做过的一道单调队列优化的DP,不是. 也是有n块木板,每个木板宽1米,有一个高度ai,现在要把他们刷成橘色,给了你一个宽一米的刷子,你可以横着刷,或 ...

  5. Offset等一些类似属性的使用

    1.offset系列 // offset 系列 var father = document.querySelector('.father'); var son = document.querySele ...

  6. [hdu4713 Permutation]DP

    题意:将一个数拆成若干数的和使得它们的最小公倍数最大 思路:一个数x可以拆成p1k1 + p2k2 + ... + pnkn形式,其中pi是质数或1.对于最小公倍数最大的情况,一定可以表示成这种形式. ...

  7. Linux 物理卷(PV)、逻辑卷(LV)、卷组(VG)管理

    (一)相关概念 逻辑卷是使用逻辑卷组管理(Logic Volume Manager)创建出来的设备,如果要了解逻辑卷,那么首先需要了解逻辑卷管理中的一些概念. 物理卷(Physical Volume, ...

  8. 想要年薪百万,阿里Sentinel支持RESTful接口都搞不定?

    最近正准备用阿里Sentinel,发现RESTful接口支持的不是很好.有些童鞋可能对Sentinel不是很了解,我们先简单介绍一下. Sentinel简介 Sentinel是一套阿里巴巴开源的流量防 ...

  9. 数学分析新讲(1) NOTE

    前言:无聊才翻翻看看来复习啦..所以慢更(●'◡'●) 1.利用求和公式的性质推导: \[\sum^{n}_{k=1}k=n \] \[\sum^{n}_{k=1}k^2=\frac{n(n+1)(2 ...

  10. .gitignore 模式匹配

    匹配模式前使用 / 表示根目录 匹配模式后使用 / 代表是目录(不是文件) 匹配模式前加 ! 表示取反 * 代表任意个字符 ? 匹配任意一个字符 ** 匹配任意级目录