`

spring IOC/DI配置

 
阅读更多

1.属性注入

public class TestAction {
	
	TestService testService;
	public void test(){
		testService.test();
	}
	
	/**
	 * 使用属性注入
	 */
	public void setTestService(TestService testService) {
		this.testService = testService;
	}
}
<bean id="testAction" class="com.chen.action.TestAction">
		<!-- 属性注入 --><property name="testService" ref="testService"></property>
	</bean>
<bean id="testService" class="com.chen.service.impl.TestServiceImpl"></bean>

 2.自动属性注入

public class TestAction {
	
	@Autowired
	TestService testService;
	public void test(){
		testService.test();
	}
}
 
<bean id="testAction" class="com.chen.action.TestAction"></bean>
<bean id="testService" class="com.chen.service.impl.TestServiceImpl"></bean>

 3.自动扫描

@Controller






public class TestAction {
	
	@Autowired
	TestService testService;
	public void test(){
		testService.test();
	}
	
	/**
	 * 使用属性注入
	 */
//	public void setTestService(TestService testService) {
//		this.testService = testService;
//	}
}

 

@Service






public class TestServiceImpl implements TestService {

	@Override
	public void test() {
		System.out.println("test");		
	}

}
 

 

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
       http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- component-scan标记包含此功能 <context:annotation-config/>-->

 <!-- 自动扫描,base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理--> 
    <context:component-scan base-package="com.chen"/>


 <!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> -->
	<!-- 
	<bean id="testAction" class="com.chen.action.TestAction">
		
	</bean>
     <bean id="testService" class="com.chen.service.impl.TestServiceImpl"></bean>
    -->
</beans>

 

参见如下两篇文章:

Spring配置项之<context:annotation-config/>

http://kld208.iteye.com/blog/1632871

 

使用 @Component

虽然我们可以通过@Autowired或@Resource在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过@Autowired或@Resource为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的@Component注释就可以达到这个目标了。

下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:


清单 20. 使用 @Component 注释的 Car.java


package com.baobaotao;

import org.springframework.stereotype.Component;

@Component

public class Car { …}




仅需要在类定义处,使用@Component注释就可以将一个类定义了 Spring 容器中的 Bean。下面的代码将Office定义为一个 Bean:


清单 21. 使用 @Component 注释的 Office.java


package com.baobaotao;

import org.springframework.stereotype.Component;

@Component

public class Office {

private String officeNo = "001";



}




这样,我们就可以在 Boss 类中通过@Autowired注入前面定义的Car和Office Bean了。


清单 22. 使用 @Component 注释的 Boss.java


package com.baobaotao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("boss")
public class Boss {
    @Autowired
    private Car car;

    @Autowired
    private Office office;
    …
}




@Component有一个可选的入参,用于指定 Bean 的名称,在 Boss 中,我们就将 Bean 名称定义为“boss”。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。

在使用@Component注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:


清单 23. 简化版的 beans.xml

Xml代码  收藏代码
  1. <? xml   version = "1.0"   encoding = "UTF-8"   ?>   
  2. < beans   xmlns = "http://www.springframework.org/schema/beans"   
  3.     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:context = "http://www.springframework.org/schema/context"   
  5.     xsi:schemaLocation ="http://www.springframework.org/schema/beans  
  6.  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.  http://www.springframework.org/schema/context  
  8.  http://www.springframework.org/schema/context/spring-context-2.5.xsd">   
  9.     < context:component-scan   base-package = "com.baobaotao" />   
  10. </ beans >   


这里,所有通过 <bean> 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 <context:component-scan/> 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan/> 的 base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。


值得注意的是 <context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessor和 CommonAnnotationBeanPostProcessor),因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。

默认情况下通过@Component定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过@Scope注释来达到目标,如以下代码所示:


清单 24. 通过 @Scope 指定 Bean 的作用范围
package com.baobaotao;
import org.springframework.context.annotation.Scope;

@Scope("prototype")
@Component("boss")
public class Boss {
    …
}


这样,当从 Spring 容器中获取bossBean 时,每次返回的都是新的实例了。

spring组件扫描<context:component-scan/>使用详解

关于spring自动检测组件的使用方式网上太多了,而且也不是我记录的重点,我想说下一点可能你还不知道的经验
我们知道如果不想在xml文件中配置bean,我们可以给我们的类加上spring组件注解,只需再配置下spring的扫描器就可以实现bean的自动载入。
 
先写一个小例子,剩下的在下面解释
<!-- 定义扫描根路径为leot.test,不使用默认的扫描方式 -->
<context:component-scan base-package="leot.test" use-default-filters="false">
  <!-- 扫描符合@Service @Repository的类 -->
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
 
下面是引用spring framework开发手册中的一段话

Spring 2.5引入了更多典型化注解(stereotype annotations): @Component@Service@Controller@Component 是所有受Spring管理组件的通用形式;而@Repository@Service@Controller 则是@Component 的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说,你能用@Component 来注解你的组件类,但如果用@Repository@Service@Controller 来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中, @Repository@Service@Controller 也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用 @Component 还是@Service ,那@Service 显然是更好的选择。同样的,就像前面说的那样, @Repository 已经能在持久化层中进行异常转换时被作为标记使用了。”

 

下面是网上目前关于组件扫描最详细的介绍

Spring applicationContext.xml的<context:component-scan>標籤用途比我想像的還要實用。而且後來才知道,有了<context:component-scan>,另一個<context:annotation-config/>標籤根本可以移除掉,因為被包含進去了。原本我survery Spring3通常只配置成<context:component-scan base-package="com.foo.bar"/>,意即在base-package下尋找有@Component和@Configuration的target Class。而現在如下的飯粒:

<context:component-scan base-package="com.foo" use-default-filters ="false">
<context:include-filter type="regex" expression="com.foo.bar.*Config"/>
<context:include-filter type="regex" expression="com.foo.config.*"/>
</context:component-scan>

  <context:component-scan>提供兩個子標籤:<context:include-filter> 和<context:exclude-filter>各代表引入和排除的過濾。而上例把use-default-filters屬性設為 false,意即在base-package所有被宣告為@Component和@Configuration等target Class不予註冊為bean,由filter子標籤代勞。

  filter標籤在Spring3有五個type,如下:

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ語法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

  所以上例用的regex就有個語病,com.foo.config.* 可以找到com.foo.config.WebLogger,但也可以找到com1fool2config3abcde,因為小數點在Regex是任意字 元,是故要用\.把小數點跳脫為佳。(2010/3/15補充:但要使用\.方式,其use-default-filters不能為false,否則抓不 到,感覺是Bug)

  Spring3提供豐富的Filter支援,有益配置策略,不需面臨Configuration Hell,比如Regex的com\.foo\.*\.action\.*Config,這樣就可以找到com.foo package下所有action子package的*Config的target class。

 

我按他的例子,配置了我自己的如下:

<context:component-scan base-package="com.xhlx.finance.budget"  >
  <context:include-filter type="regex" expression="com.lee.finance.budget.service.*"/>
  <context:include-filter type="regex" expression="com.lee.finance.budget.security.*"/> 
</context:component-scan>
但是死活扫描不到,网上又没有更好的讲解,没办法只好自己试,改成
<context:component-scan base-package="com.xhlx.finance.budget" >
  <context:include-filter type="regex" expression="com.lee.finance.budget.*"/>
</context:component-scan>
这样连没有加注解的类也扫描并实例化,结果报错,因为有的类根本就没有默认的构造函数不能实例化,能不报错吗
改成
<context:component-scan base-package="com.xhlx.finance.budget"  >
  <context:include-filter type="regex" expression="com\.lee\.finance\.budget\.service.*"/>  
</context:component-scan>问题依旧
<context:component-scan base-package="com.xhlx.finance.budget" >
  <context:include-filter type="regex" expression="com.lee.finance.budget.service.TestService"/>
</context:component-scan>
嘿,这次可以了,写全限定名就可以,表达式却不行,但是如果我有成千上百个还得一个一个这样配置啊?不行,继续研究,我想有个base-package的配置,从表面意思来看这是个“基本包”,是否表示下面的过滤路径是基于这个包的呢?于是试着改成
<context:component-scan base-package="com.xhlx.finance.budget" >
  <context:include-filter type="regex" expression=".service.*"/>
</context:component-scan>
嘿,行了。 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    使用Spring IOC/DI 模拟某超市管理功能

    (1)Product类(商品类):含id(商品编号)、proName(商品名称)、price(价格),并为所有属性生成get和set方法。 (2)Market类(超市类):含marketName(超市名称)、productArr(仓库,List集合) ...

    springIOC和DI

    什么是spring,spring核心,spring优点,spring体系结构, 入门案例,DI基础,核心API,文档内附代码

    jBeanBox是一个微形但功能较齐全的IOC/AOP工具,用于Java6或以上环境

    jBeanBox项目的定位:需要一个功能较全的IOC/AOP工具,但是又不想引入臃肿的Spring。 其它IOC/AOP工具的问题: Spring: 源码臃肿,Java方式的配置不灵活, 非单例模式时性能差。 Guice: 源码臃肿(200多个类),手工...

    笔记28-JAVAEE之Spring IoC&DI

    笔记28-JAVAEE之Spring IoC&DI

    day-Spring IoC & DI.md

    day-Spring IoC & DI.md

    SpringIOC,DI+dynamic proxy 实现盗版AOP

    SpringIOC,DI+dynamic proxy 实现盗版AOP的源代码

    SpringIoC和DI注解开发.pdf

    SpringIoC和DI注解开发.pdf

    Springioc注入Demo

    详细讲解了springioc的各种注入方式以及对应的java方式。讲解了springioc和DI的区别,以及注入特殊复杂的属性

    day2-Spring IOC 和 DI 注解开发.md

    day2-Spring IOC 和 DI 注解开发.md

    Spring IOC和DI实现原理及实例解析

    主要介绍了Spring IOC和DI实现原理及实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    什么是Ioc和DI

    什么是Ioc和DI

    Spring IOC AOP MVC 简单例子

    Spring IOC AOP MVC 简单例子

    Spring IOC部分经典教程

    该教程详细介绍了spring的构架结构,ioc/di思想的转变过程。是一本不可多得的spring入门教程。

    spring ioc di aop详解

    spring ioc di aop详解

    spring框架约束步骤及教程

    spring-beans.jar 这个jar文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean及进行Inversion of Control / Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI支持,引入...

    springIOC核心组件分析.vsdx

    spring-core:核心模块 依赖注入IOC和DI的最基本实现 spring-beans:Bean工厂与装配 spring-context:上下文,即IOC容器 spring-context-support:对IOC的扩展,以及IOC子容器 spring-context-indexer:类管理组件和...

    springioc和spring aop

    控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找...

    spring jar包

    3.spring-beans:基础jar包,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control / Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring...

    Spring源码解析4章150页+Spring3.2.4中文注释源码

    2、SpringIOC体系结构 3、源码分析-IOC容器的初始化 4、源码分析-IOC容器的依赖注入 5、源码分析-IOC容器的高级特性 三阶段 Spring AOP的涉及原理及具体实践 SpringJDBC的涉及原理及二次开发 SpringMVC框架设计原理...

    关于spring的AOP ,IOC,DI的理解

    帮助初学者理解spring框架,有助于提高代码能力java.sql.SQLException: Duplicate entry '2' for key 'PRIMARY' Query: insert into transaction values(?,?,?,?,?) Parameters: [2, 6212999999999, 转出, 6000000, ...

Global site tag (gtag.js) - Google Analytics