Spring基础知识

简介: Spring基础知识利用spring完成松耦合接口public interface IOutputGenerator{ public void generateOutput();}实现类csv输出public class CsvOutputGenerator implemen...

Spring基础知识

利用spring完成松耦合

接口

public interface IOutputGenerator
{
    public void generateOutput();
}

实现类

csv输出

public class CsvOutputGenerator implements IOutputGenerator
{
    public void generateOutput(){
        System.out.println("Csv Output Generator");
    }
}

json输出

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;
    }
}

bean类配置文件

<!-- 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>

    <bean id="CsvOutputGenerator" class="com.springtest.output.impl.CsvOutputGenerator" />
    <bean id="JsonOutputGenerator" class="com.springtest.output.impl.JsonOutputGenerator" />

</beans>

调用方式

public static void main( String[] args )
{
  ApplicationContext context =
     new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});

  OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
  output.generateOutput();

}

结论

通过spring bean的方式进行配置可以灵活地将不同需求通过配置文件来完成,而不是改java原代码。通过面向接口的编程并结合spring的配置便可达到解耦的目的。

Spring JavaConfig实例

通常我们是通过xml的方式进行bean的声明

<bean id="helloBean" class="com.springtest.hello.impl.HelloWorldImpl">

使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,并通过 @Bean 定义 bean。

@Configuration
public class AppConfig {

    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }

}

Spring依赖注入(DI)

spring有两种注入的方式

  • setter方法注入
  • getter方法注入

setter方法注入

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" />
  </property>
</bean>

<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">
  <constructor-arg>
    <bean class="com.springtest.output.impl.CsvOutputGenerator" />
  </constructor-arg>
</bean>

<bean id="CsvOutputGenerator" class="com.springtest.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.springtest.output.impl.JsonOutputGenerator" />

Spring Bean引用

Bean在不同的XML文件

<ref bean="someBean"/>

在同一个XML文件中的Bean

<ref local="someBean"/>

Spring bean属性值的注入

  • 正常的方式
  • 快捷方式
  • p模式

正常的方式

在一个value标签注入值,并附有property标签结束。

<bean id="FileNameGenerator" class="com.springtest.common.FileNameGenerator">
  <property name="name">
    <value>springtest</value>
  </property>
  <property name="type">
    <value>txt</value>
  </property>
</bean>

快捷方式

<property name="type" value="txt" />

<bean id="FileNameGenerator" class="com.springtest.common.FileNameGenerator">
  <property name="name" value="springtest" />
  <property name="type" value="txt" />
</bean>

p模式

<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"/>

</beans>

加载方式

ApplicationContext context =
            new ClassPathXmlApplicationContext(Spring-All-Module.xml);

spring内部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">
        <property name="person" ref="PersonBean" />
    </bean>

    <bean id="PersonBean" class="com.springtest.common.Person">
        <property name="name" value="springtest" />
        <property name="address" value="address1" />
        <property name="age" value="28" />
    </bean>

</beans>

如果一个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">
        <property name="person">
            <bean class="com.springtest.common.Person">
                <property name="name" value="springtest" />
                <property name="address" value="address1" />
                <property name="age" value="28" />
            </bean>
        </property>
    </bean>
</beans>

或

<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">
        <constructor-arg>
            <bean class="com.springtest.common.Person">
                <property name="name" value="springtest" />
                <property name="address" value="address1" />
                <property name="age" value="28" />
            </bean>
        </constructor-arg>
    </bean>
</beans>

Spring Bean作用域

在Spring中,bean作用域用于确定哪种类型的 bean 实例应该从Spring容器中返回给调用者。bean支持的5种范围域:

  • 单例 - 每个Spring IoC 容器返回一个bean实例
  • 原型- 当每次请求时返回一个新的bean实例
  • 请求 - 返回每个HTTP请求的一个Bean实例
  • 会话 - 返回每个HTTP会话的一个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"
      scope="prototype"/>

此外还可以通过注解的方式来指定作用域。

Spring集合 (List,Set,Map,Properties)

spring支持4个主要的集合类型。

  • List – <list/>
  • Set – <set/>
  • Map – <map/>
  • Properties – <props/>

List注入方式

<property name="lists">
    <list>
        <value>1</value>
        <ref bean="PersonBean" />
        <bean class="com.springtest.common.Person">
            <property name="name" value="springtestList" />
            <property name="address" value="Hainan" />
            <property name="age" value="28" />
        </bean>
    </list>
</property>

Set注入方式

<property name="sets">
    <set>
        <value>1</value>
        <ref bean="PersonBean" />
        <bean class="com.springtest.common.Person">
            <property name="name" value="springtestSet" />
            <property name="address" value="Hainan" />
            <property name="age" value="28" />
        </bean>
    </set>
</property>

Map注入方式

<property name="maps">
    <map>
        <entry key="Key 1" value="1" />
        <entry key="Key 2" value-ref="PersonBean" />
        <entry key="Key 3">
            <bean class="com.springtest.common.Person">
                <property name="name" value="springtestMap" />
                <property name="address" value="Hainan" />
                <property name="age" value="28" />
            </bean>
        </entry>
    </map>
</property>

Properties注入方式

<property name="pros">
        <props>
            <prop key="admin">admin@springtest.com</prop>
            <prop key="support">support@springtest.com</prop>
        </props>
    </property>

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">
        <property name="lists">
            <bean class="org.springframework.beans.factory.config.ListFactoryBean">
                <property name="targetListClass">
                    <value>java.util.ArrayList</value>
                </property>
                <property name="sourceList">
                    <list>
                        <value>one</value>
                        <value>2</value>
                        <value>three</value>
                    </list>
                </property>
            </bean>
        </property>
    </bean>

</beans>

方式二

通过

<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">
        <property name="lists">
            <util:list list-class="java.util.ArrayList">
                <value>one</value>
                <value>2</value>
                <value>three</value>
            </util:list>
        </property>
    </bean>

</beans>

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">
        <property name="sets">
            <bean class="org.springframework.beans.factory.config.SetFactoryBean">
                <property name="targetSetClass">
                    <value>java.util.HashSet</value>
                </property>
                <property name="sourceSet">
                    <list>
                        <value>one</value>
                        <value>2</value>
                        <value>three</value>
                    </list>
                </property>
            </bean>
        </property>
    </bean>

</beans>

方式二

通过<util:set></util:set>

<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">
        <property name="sets">
            <util:set set-class="java.util.HashSet">
                <value>one</value>
                <value>2</value>
                <value>three</value>
            </util:set>
        </property>
    </bean>

</beans>

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">
        <property name="maps">
            <bean class="org.springframework.beans.factory.config.MapFactoryBean">
                <property name="targetMapClass">
                    <value>java.util.HashMap</value>
                </property>
                <property name="sourceMap">
                    <map>
                        <entry key="Key1" value="one" />
                        <entry key="Key2" value="two" />
                        <entry key="Key3" value="three" />
                    </map>
                </property>
            </bean>
        </property>
    </bean>

</beans>

方式二

通过<util:map></util:map>

<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">
        <property name="maps">
            <util:map map-class="java.util.HashMap">
                <entry key="Key1" value="1" />
                <entry key="Key2" value="2" />
                <entry key="Key3" value="3" />
            </util:map>
        </property>
    </bean>

</beans>

Spring PropertyPlaceholderConfigurer数据库配置

pom.xml中添加依赖

<!-- mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.38</version>
</dependency>

<!-- druid -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.20</version>
</dependency>

属性配置文件:system-config.properties

################################################
# DataSource Config
jdbc.url=jdbc\:mysql\://127.0.0.1:3306/quartz?useUnicode\=true&characterEncoding\=utf8&autoReconnect\=true&useSSL\=false&zeroDateTimeBehavior\=convertToNull
jdbc.username=root
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">
            <list>
                <value>classpath:system-config.properties</value>
            </list>
        </property>
    </bean>

    <!-- 防SQL注入过滤器 -->
    <bean id="wall-filter" class="com.alibaba.druid.wall.WallFilter">
        <property name="dbType" value="mysql" />
    </bean>
    <!-- 监控信息过滤器 -->
    <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>

    <!-- 数据源 -->
    <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">
            <list>
                <!-- 监控信息过滤器 -->
                <ref bean="stat-filter" />
                <!-- 防注入的话从前台传排序字段排序不好用 -->
                <ref bean="wall-filter" />
            </list>
        </property>
    </bean>

</beans>

Spring bean配置继承

在 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>

    <bean id="CustomerBean" parent="BaseCustomerMalaysia">
        <property name="action" value="buy" />
        <property name="type" value="1" />
    </bean>

</beans>

继承抽象

如果你要让这个 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>

    <bean id="CustomerBean" parent="BaseCustomerMalaysia">
        <property name="action" value="buy" />
        <property name="type" value="1" />
    </bean>

</beans>

如果想实例化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>

    <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" />
    </bean>

</beans>

Spring依赖检查

在Spring中,可以使用依赖检查功能,以确保所要求的属性可设置或者注入。

依赖检查模式

4个依赖检查支持的模式:

  • none – 没有依赖检查,这是默认的模式。
  • simple – 如果基本类型(int, long,double…)和集合类型(map, list..)的任何属性都没有设置,UnsatisfiedDependencyException将被抛出。
  • objects – 如果对象类型的任何属性都没有设置,UnsatisfiedDependencyException将被抛出。
  • all – 如果任何类型的任何属性都没有被设置,UnsatisfiedDependencyException将被抛出。

注:默认模式是 none

dependency-check="simple"

<bean id="CustomerBean" class="com.springtest.common.Customer"
       dependency-check="simple">

  <property name="person" ref="PersonBean" />
  <property name="action" value="buy" />
</bean>

Spring 特定属性依赖检查

通过dependency-check的方式进行依赖检查是对整个类型的属性都进行了检查。然而大多数情况下只需要对某个属性进行检查即可。因此引入了@Required注解对某个属性进行检查。

配置文件设置

方式一

添加 Spring 上下文和 <context:annotation-config />在bean配置文件。

<beans
    ...
    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 />
    ...
</beans>

方式二

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

** bean 设置 **

在对应属性的set方法上添加@Required。

@Required
public void setPerson(Person person) {
  this.person = person;
}

Spring自定义@Required-style注解

创建注解接口Mandatory(名称可以自己起)

@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"/>
</bean>

注解引用

@Mandatory
public void setPerson(Person person) {
  this.person = person;
}

至此,创建了一个新的自定义命名 @Required-style的@Mandatory 注解,相当于 @Required 注解。

spring bean初始化准备和销毁清理

方式一:

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" />
    </bean>

</beans>

方式三

使用@PostConstruct 和 @PreDestroy 注解

  • 注:@PostConstruct和@PreDestroy 标注不属于 Spring,它是在J2EE库- common-annotations.jar。

添加注解扫描

通过CommonAnnotationBeanPostProcessor的方式

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

通过<context:annotation-config />的方式

<context:annotation-config />

注解应用

@PostConstruct
public void initIt() throws Exception {
  System.out.println("Init method after properties are set : " + message);
}

@PreDestroy
public void cleanUp() throws Exception {
  System.out.println("Spring Container is destroy! Customer clean up");
}

spring el表达式

略

spring 自动扫描组件

  • @Entity实体bean
  • @Service用于标注业务层组件
  • @Controller用于标注控制层组件(如struts中的action)
  • @Repository用于标注数据访问组件,即DAO组件
  • @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

注册扫描组件

<context:component-scan base-package="com.springtest.customer" />

Spring过滤器组件自动扫描

添加过滤器

不包含过滤器

<!-- 只需要加载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>

一般结合spring mvc自动扫描组件一起用

<!-- 扫描所有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>

</beans>

Spring自动注入Beans实体

通过autowire(此种方式基本不用了)属性和@Autowired (一般采用这种方式进行处理)注解

autowire

autowire提供5种装配方式。

  • no – 缺省情况下,自动配置是通过“ref”属性手动设定
  • byName – 根据属性名称自动装配。如果一个bean的名称和其他bean属性的名称是一样的,将会自装配它。
  • byType – 按数据类型自动装配。如果一个bean的数据类型是用其它bean属性的数据类型,兼容并自动装配它。
  • constructor – 在构造函数参数的byType方式。
  • autodetect – 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。
<bean id="customer" class="com.springtest.common.Customer" autowire="byName" />

**@Autowired**

  • 建议采用此种方式。

注册AutowiredAnnotationBeanPostProcessor

方式1:

<context:annotation-config />

方式2:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

使用

@Autowired
    private Person person;

Spring AOP切面(Advice)编程

可以有多种方式,其中面向方法的切面可参考,Spring AOP基于配置文件的面向方法的切面

jdbc操作

略

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
缓存 安全 IDE
Java 必看的 Spring 知识汇总!
Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性的角度而言,绝大部分Java应用都可以从Spring中受益。
368 0
Java 必看的 Spring 知识汇总!
|
XML Java 数据格式
Spring基本知识总结
Spring基本知识总结
|
容器 Spring Java
Spring小知识2
Spring小知识
1130 0
|
Java Spring 数据格式
Spring小知识
Spring小知识
1096 0
|
Java 容器 Spring
spring主要知识
----------------------------------------------------------------------------------Spring基础 1.spring的标签:轻量化 、 分层框架 、7个模块 、统一构建与核心容器之上。
1268 0
|
前端开发 Java 数据格式
有关Spring注解@xxx的零碎知识
 在Java的Spring开发中经常使用一些注解,例如 @XXX 等等,在网上看到收集整理碎片知识,便于懒人计划^=^... 过去,Spring使用的Java Bean对象必须在配置文件[一般为application.xml] 中进行配置,然后才能使用,但Spring2.5版之后,引入了配置注解功能,操作更简单,但是不了解的就抽象了,所以有必要了解一下一些注解的知识; 一,首选注
1593 0
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1656 0
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1657 0
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
702 0
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
1353 0