public interface IOutputGenerator
public void generateOutput();
public class CsvOutputGenerator implements IOutputGenerator
public void generateOutput(){
System.out.println("Csv Output Generator");
public class JsonOutputGenerator implements IOutputGenerator
public void generateOutput(){
System.out.println("Json Output Generator");
public class OutputHelper
IOutputGenerator outputGenerator;
public void generateOutput(){
outputGenerator.generateOutput();
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
<!-- Spring-Common.xml -->
<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-2.5.xsd">
<bean id="OutputHelper" class="com.springtest.output.OutputHelper">
<property name="outputGenerator" ref="CsvOutputGenerator" />
<bean id="CsvOutputGenerator" class="com.springtest.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.springtest.output.impl.JsonOutputGenerator" />
public static void main( String[] args )
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
通过spring bean的方式进行配置可以灵活地将不同需求通过配置文件来完成,而不是改java原代码。通过面向接口的编程并结合spring的配置便可达到解耦的目的。
<bean id="helloBean" class="com.springtest.hello.impl.HelloWorldImpl">
使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,并通过 @Bean 定义 bean。
public HelloWorld helloWorld() {
return new HelloWorldImpl();
public class OutputHelper
IOutputGenerator outputGenerator;
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
<bean id="OutputHelper" class="com.springtest.output.OutputHelper">
<property name="outputGenerator">
<ref bean="CsvOutputGenerator" />
<bean id="CsvOutputGenerator" class="com.springtest.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.springtest.output.impl.JsonOutputGenerator" />
public class OutputHelper
IOutputGenerator outputGenerator;
OutputHelper(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
<bean id="OutputHelper" class="com.springtest.output.OutputHelper">
<bean class="com.springtest.output.impl.CsvOutputGenerator" />
<bean id="CsvOutputGenerator" class="com.springtest.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.springtest.output.impl.JsonOutputGenerator" />
在一个value标签注入值,并附有property标签结束。
<bean id="FileNameGenerator" class="com.springtest.common.FileNameGenerator">
<value>springtest</value>
<property name="type" value="txt" />
<bean id="FileNameGenerator" class="com.springtest.common.FileNameGenerator">
<property name="name" value="springtest" />
<property name="type" value="txt" />
<bean id="FileNameGenerator" class="com.springtest.common.FileNameGenerator"
p:name="springtest" p:type="txt" />
<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-2.5.xsd">
<import resource="common/Spring-Common.xml"/>
<import resource="connection/Spring-Connection.xml"/>
<import resource="moduleA/Spring-ModuleA.xml"/>
ApplicationContext context =
new ClassPathXmlApplicationContext(Spring-All-Module.xml);
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<property name="person" ref="PersonBean" />
<bean id="PersonBean" class="com.springtest.common.Person">
<property name="name" value="springtest" />
<property name="address" value="address1" />
<property name="age" value="28" />
如果一个bean仅仅是作为一个bean的内部bean。那么可以声明为内部bean。
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<bean class="com.springtest.common.Person">
<property name="name" value="springtest" />
<property name="address" value="address1" />
<property name="age" value="28" />
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<bean class="com.springtest.common.Person">
<property name="name" value="springtest" />
<property name="address" value="address1" />
<property name="age" value="28" />
在Spring中,bean作用域用于确定哪种类型的 bean 实例应该从Spring容器中返回给调用者。bean支持的5种范围域:
单例 - 每个Spring IoC 容器返回一个bean实例
全局会话- 返回全局HTTP会话的一个bean实例
在大多数情况下,可能只处理了 Spring 的核心作用域 - 单例和原型,默认作用域是单例。
注:意味着只有在一个基于web的Spring ApplicationContext情形下有效!
<bean id="customerService"
class="com.springtest.customer.services.CustomerService" />
bean声明时添加scope="prototype"属性。
<bean id="customerService" class="com.springtest.customer.services.CustomerService"
Spring集合 (List,Set,Map,Properties)
<ref bean="PersonBean" />
<bean class="com.springtest.common.Person">
<property name="name" value="springtestList" />
<property name="address" value="Hainan" />
<property name="age" value="28" />
<ref bean="PersonBean" />
<bean class="com.springtest.common.Person">
<property name="name" value="springtestSet" />
<property name="address" value="Hainan" />
<property name="age" value="28" />
<entry key="Key 1" value="1" />
<entry key="Key 2" value-ref="PersonBean" />
<bean class="com.springtest.common.Person">
<property name="name" value="springtestMap" />
<property name="address" value="Hainan" />
<property name="age" value="28" />
<prop key="admin">admin@springtest.com</prop>
<prop key="support">support@springtest.com</prop>
Spring ListFactoryBean 创建一个具体的列表集合类(ArrayList和LinkedList)
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<bean class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="targetListClass">
<value>java.util.ArrayList</value>
<property name="sourceList">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<util:list list-class="java.util.ArrayList">
Spring SetFactoryBean创建一个具体的Set集合(HashSet 和 TreeSet)
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<bean class="org.springframework.beans.factory.config.SetFactoryBean">
<property name="targetSetClass">
<value>java.util.HashSet</value>
<property name="sourceSet">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<util:set set-class="java.util.HashSet">
Spring MapFactoryBean创建一个具体的Map集合类(HashMap和TreeMap)
<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-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<bean class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="targetMapClass">
<value>java.util.HashMap</value>
<property name="sourceMap">
<entry key="Key1" value="one" />
<entry key="Key2" value="two" />
<entry key="Key3" value="three" />
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.springtest.common.Customer">
<util:map map-class="java.util.HashMap">
<entry key="Key1" value="1" />
<entry key="Key2" value="2" />
<entry key="Key3" value="3" />
Spring PropertyPlaceholderConfigurer数据库配置
<!-- mysql-connector-java -->
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
属性配置文件:system-config.properties
################################################
jdbc.url=jdbc\:mysql\://127.0.0.1:3306/quartz?useUnicode\=true&characterEncoding\=utf8&autoReconnect\=true&useSSL\=false&zeroDateTimeBehavior\=convertToNull
jdbc.publicKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALIT9sFn8U+Hoo80Q+Hepwc0ZN6HBiyAW4SiLCXLhNNjxB45mtRamABoB0O9dEsziT/gwtuXMuC2bWePdCvEb1ECAwEAAQ==
jdbc.password=fCHxOiDBDsWY/BJLg05fbNGvQmDRPZJufcvyqCqml+zwmB4Gw/Bn7lzy8w117CQ1jEBFpj0ERgQsCBJD0ROfJw==
applicationContext.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 只需要加载service、dao即可,不需要加载controller -->
<context:component-scan base-package="com.quartz">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:system-config.properties</value>
<bean id="wall-filter" class="com.alibaba.druid.wall.WallFilter">
<property name="dbType" value="mysql" />
<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
<!-- slowSqlMillis用来配置SQL慢的标准,执行时间超过slowSqlMillis的就是慢。 -->
<property name="slowSqlMillis" value="10000" />
<property name="logSlowSql" value="true" />
<property name="mergeSql" value="true" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="filters" value="config" />
<property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${jdbc.publicKey}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="5" />
<property name="minIdle" value="5" />
<property name="maxActive" value="30" />
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<property name="removeAbandoned" value="true" />
<!-- 超时时间;单位为秒。180秒=3分钟 -->
<property name="removeAbandonedTimeout" value="180" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<property name="proxyFilters">
<ref bean="stat-filter" />
<!-- 防注入的话从前台传排序字段排序不好用 -->
<ref bean="wall-filter" />
在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置。可通过parent属性进行配置。
一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性。另外,子 Bean 允许覆盖继承的值。
<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-2.5.xsd">
<bean id="BaseCustomerMalaysia" class="com.springtest.common.Customer">
<property name="country" value="Malaysia" />
<bean id="CustomerBean" parent="BaseCustomerMalaysia">
<property name="action" value="buy" />
<property name="type" value="1" />
如果你要让这个 bean 作为一个基础模板,不允许别人来实例化它,可以在一个元素中添加一个abstract的属性。
<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-2.5.xsd">
<bean id="BaseCustomerMalaysia" class="com.springtest.common.Customer" abstract="true">
<property name="country" value="Malaysia" />
<bean id="CustomerBean" parent="BaseCustomerMalaysia">
<property name="action" value="buy" />
<property name="type" value="1" />
如果想实例化BaseCustomerMalaysia则会报错。
父 bean 是不需要定义类的属性,很多时候,你可能只需要一个共同的属性共享。
<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-2.5.xsd">
<bean id="BaseCustomerMalaysia" abstract="true">
<property name="country" value="Malaysia" />
<bean id="CustomerBean" parent="BaseCustomerMalaysia"
class="com.springtest.common.Customer">
<property name="country" value="Japan" /> <!--覆盖-->
<property name="action" value="buy" />
<property name="type" value="1" />
在Spring中,可以使用依赖检查功能,以确保所要求的属性可设置或者注入。
simple – 如果基本类型(int, long,double…)和集合类型(map, list..)的任何属性都没有设置,UnsatisfiedDependencyException将被抛出。
objects – 如果对象类型的任何属性都没有设置,UnsatisfiedDependencyException将被抛出。
all – 如果任何类型的任何属性都没有被设置,UnsatisfiedDependencyException将被抛出。
dependency-check="simple"
<bean id="CustomerBean" class="com.springtest.common.Customer"
dependency-check="simple">
<property name="person" ref="PersonBean" />
<property name="action" value="buy" />
通过dependency-check的方式进行依赖检查是对整个类型的属性都进行了检查。然而大多数情况下只需要对某个属性进行检查即可。因此引入了@Required注解对某个属性进行检查。
添加 Spring 上下文和 <context:annotation-config />在bean配置文件。
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
public void setPerson(Person person) {
Spring自定义@Required-style注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
<property name="requiredAnnotationType" value="com.springtest.common.Mandatory"/>
public void setPerson(Person person) {
至此,创建了一个新的自定义命名 @Required-style的@Mandatory 注解,相当于 @Required 注解。
Spring Bean InitializingBean和DisposableBean
如果bean实现了InitializingBean,则afterPropertiesSet()会在所有的 bean 属性设置后执行。
如果bean实现了DisposableBean,则destroy()会在Spring容器释放后执行。
注意:但不建议这样使用。因为这样增加了代码与spring的耦合度。
因此建议使用init-method 和 destroy-method
<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-2.5.xsd">
<bean id="customerService" class="com.springtest.customer.services.CustomerService"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="i'm property message" />
使用@PostConstruct 和 @PreDestroy 注解
注:@PostConstruct和@PreDestroy 标注不属于 Spring,它是在J2EE库- common-annotations.jar。
通过CommonAnnotationBeanPostProcessor的方式
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
通过<context:annotation-config />的方式
<context:annotation-config />
public void initIt() throws Exception {
System.out.println("Init method after properties are set : " + message);
public void cleanUp() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
<context:component-scan base-package="com.springtest.customer" />
<!-- 只需要加载service、dao即可,不需要加载controller -->
<context:component-scan base-package="com.springtest">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- 扫描所有controller组件 -->
<context:component-scan base-package="com.quartz">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!--注册requestmapping,否则无法扫描@RequestMapping的注解-->
<mvc:annotation-driven />
<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.springtest" >
<context:include-filter type="regex"
expression="com.springtest.customer.dao.*DAO.*" />
<context:include-filter type="regex"
expression="com.springtest.customer.services.*Service.*" />
</context:component-scan>
通过autowire(此种方式基本不用了)属性和@Autowired (一般采用这种方式进行处理)注解
no – 缺省情况下,自动配置是通过“ref”属性手动设定
byName – 根据属性名称自动装配。如果一个bean的名称和其他bean属性的名称是一样的,将会自装配它。
byType – 按数据类型自动装配。如果一个bean的数据类型是用其它bean属性的数据类型,兼容并自动装配它。
constructor – 在构造函数参数的byType方式。
autodetect – 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。
<bean id="customer" class="com.springtest.common.Customer" autowire="byName" />
注册AutowiredAnnotationBeanPostProcessor
<context:annotation-config />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
可以有多种方式,其中面向方法的切面可参考,Spring AOP基于配置文件的面向方法的切面
略
本文转自秋楓博客园博客,原文链接:http://www.cnblogs.com/rwxwsblog/p/5870948.html,如需转载请自行联系原作者