Spring学习笔记

Spring配置元数据3种方式
  • 基于xml的配置文件
  • 基于注解的配置

    例如 通过 <context:component-scan base-package="com.company.">
    spring自动扫描带有@Component、@Repository、@Service、@Controller标签的类自动注册到spring容器.以及对标记了@Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效(包含了annotation-config标签的作用)。

    getBean()的默认名称是类名(头字母小写),如果想自定义,可以@Service("aaaaa")这样来指定。
    这种bean默认是"singleton"的,如果想改变,可以使用@Scope("prototype")来改变,以及自定义初始化和销毁方法等.

    @PostConstruct  
    public void init() {...}   
    @PreDestroy  
    public void destory() {...}   

    使用@Autowired自动注解接口的时候,如果该接口有多个 实现,需要@Qualifier指定注入哪个实现类

  • 基于java的配置

@Autowired用法和流程

@Autowired, 可以用在以下三个地方
- 属性
如果用在属性上, 可以不用谢setter方法.
- setter方法
如果用在setter方法上,可以不用写手动set,会自动注入
- 构造函数
如果用在构造函数上, 可以不用在xml文件中配置bean的 constructor-arg的参数.

@Autowired是如何自动注入的??

首先根据配置文件的bean的id, 如果id找不到就找name, 继续找不到就找类型,
即如下顺序:

当根据Type进行自动注入时, 如果有多个相同Type(比如一个接口有多个实现), 就需要@Qualifier这个注解了, Qualifier里面可以写id或者name.

如果根据id或者name注入时,参数/属性的变量名必须和id/name完全一致.
比如:

private Hello hello;
 <bean id="hello" clas="com.company.HelloWorld"/>
 <bean id="hello2" clas="com.company.HelloChina"/>
bean的作用域
作用域描述
singleton该作用域将 bean 的定义的限制在每一个 Spring IoC 容器中的一个单一实例(默认)。
prototype该作用域将单一 bean 的定义限制在任意数量的对象实例。
request该作用域将 bean 的定义限制为 HTTP 请求。只在 web-aware Spring ApplicationContext 的上下文中有效。
session该作用域将 bean 的定义限制为 HTTP 会话。 只在web-aware Spring ApplicationContext的上下文中有效。
global-session该作用域将 bean 的定义限制为全局 HTTP 会话。只在 web-aware Spring ApplicationContext 的上下文中有效

当使用scope="singleton"的时候,每次getbeean()调用的为同样一个实例, 使用scope="prototype"时,每次都是一个新的实例

初始化回调与销毁回调

java实现

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;
...
public class ExampleBean implements InitializingBean,
     DisposableBean{
    public void afterPropertiesSet() {
    // do some initialization work  
    }
    public void destroy() {
        // do some destruction work
    }
    ...
}

或者基于xml配置

<bean id="exampleBean"
    class="examples.ExampleBean"
    init-method="init"
    destroy-method="destroy"/>
...
public class ExampleBean {
    public void init() {
        // do some initialization work
    }
    public void destroy() {
        // do some destruction work
    }
}

建议不要使用 InitializingBean 或者 DisposableBean 的回调方法,因为 XML 配置在命名方法上提供了极大
的灵活性

提供所有bean默认的初始化和销毁方法

如果你有太多具有相同名称的初始化或者销毁方法的 Bean,那么你不需要在每一个 bean 上声明 初始化方法和
销毁方法。框架使用 元素中的 d default-init-method 和 d default-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-3.0.xsd"
    default-init-method="init"
    default-destroy-method="destroy">

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>
</beans>
注入集合
list, set, map, prorps
<property name="list">
    <list>
        <ref bean="helloChina"/>
        <value>hello</value>
        <value>hi</value>
    </list>
</property>
<property name="map">
    <map>
        <entry key="1" value="INDIA"/>
        <entry key="2" value="USA"/>
    </map>
</property>
<property name="set">
    <set>
        <value>INDIA</value>
        <value>USA</value>
    </set>
</property>
p-namespace简化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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="john-classic" class="com.example.Person">
        <property name="name" value="John Doe"/>
        <property name="spouse" ref="jane"/>
    </bean>
    <bean name="jane" class="com.example.Person">
        <property name="name" value="John Doe"/>
    </bean>
</beans>
------------------
<?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-3.0.xsd">

    <bean id="john-classic" class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/> <!-- -ref部分表明引用 -->
    </bean>
    <bean name="jane" class="com.example.Person"
        p:name="John Doe"/>
    </bean>
</beans>
Spring-AOP
aop命名空间标签
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- bean definition & AOP specific configuration -->
</beans>

配置依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.9</version>
</dependency>
声明一个切入点
  • 基于xml配置
<aop:config>
    <aop:aspect id="myAspect" ref="aBean">
        <aop:pointcut id="businessService"
            expression="execution(* com.xyz.myapp.service.*.*(..))"/>
        <!-- a before advice definition -->
        <aop:before pointcut-ref="businessService" method="doRequiredTask"/>
        <!-- an after advice definition -->
        <aop:after pointcut-ref="businessService" method="doRequiredTask"/>

        <!-- an after-returning advice definition -->
        <!--The doRequiredTask method must have parameter named retVal -->
        <aop:after-returning pointcut-ref="businessService" returning="retVal" method="doRequiredTask"/>

        <!-- an after-throwing advice definition -->
        <!--The doRequiredTask method must have parameter named ex -->
        <aop:after-throwing pointcut-ref="businessService" throwing="ex" method="doRequiredTask"/>

        <!-- an around advice definition -->
        <aop:around pointcut-ref="businessService" method="doRequiredTask"/>
        ...
    </aop:aspect>
</aop:config>
<bean id="aBean" class="...">
...
</bean>

(..)表示方法可能有参数.

  • 通过注解配置
    xml中添加<aop:aspectj-autoproxy/>
    配置实例:
@Aspect
public class AspectModule {
    @Pointcut("execution(* com.hand.aop.Hello.test())")
    private void testService(){}
    @Before("testService()")
    public void doBeforeTask() {
        System.out.println("before task");
    }
    @After("testService()")
    public void doAfterTask(){
        System.out.println("after task");
    }
    @AfterReturning(pointcut = "testService()", returning="retVal")
    public void doAfterReturnningTask(Object retVal){
        System.out.println("doAfterReturnningTask");
    }
    @AfterThrowing(pointcut = "testService()", throwing="ex")
    public void doAfterThrowingTask(Exception ex){
        System.out.println("doAfterThrowingTask");
    }
    @Around("testService()")
    public void doAroundTask() {
        System.out.println("doAroundTask");
    }
}
---
<bean id="aspectModule" class="com.company.AspectModule"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值