初见

spring 配置、注解理解

2019-02-18  本文已影响0人  九草
<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"
   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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  http://www.springframework.org/schema/context     
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <bean name="c" class="对应类1">
       <property name="name" value="category 1" />
   </bean>
   <bean name="p" class="对应类2(属性中有类1)">
       <property name="name" value="product1" />
       <property name="category" ref="c" />
   </bean>

</beans>
       类2 p = (类2) context.getBean("p");
        System.out.println(p.getName());
        System.out.println(p.get类1().getName());
  <context:annotation-config/>
     <bean name="c" class="对应类1">
        <property name="name" value="category 1" />
    </bean>
    <bean name="p" class="对应类2(属性中有类1)">
        <property name="name" value="product1" />
   <!--     <property name="category" ref="c" />-->
    </bean>

@Autowired
private 类1  category;

@Autowired
public void setCategory(Category category) 

@Resource(name="c")
private 类1 category;
xml只有:
 <context:component-scan base-package="包名"/>

为Product类加上@Component注解,即表明此类是bean
@Component("p")
public class Product {

<bean name="s" class="com.service.ProductService">
</bean>
声明业务对象
<bean id="loggerAspect" class="com.aspect.LoggerAspect"/>
声明日志切面
<aop:pointcut id="loggerCutpoint"
expression=
"execution(* com.service.ProductService.(..)) "/>
指定右边的核心业务功能
<aop:aspect id="logAspect" ref="loggerAspect">
<aop:around pointcut-ref="loggerCutpoint" method="log"/>
</aop:aspect>
指定左边的辅助功能
然后通过aop:config把业务对象与辅助功能编织在一起。
execution(
com.service.ProductService.(..))
这表示对满足如下条件的方法调用,进行切面操作: * 返回任意类型
com.service.ProductService.

包名以 com.service.ProductService 开头的类的任意方法
(..) 参数是任意数量和类型

@Aspect 注解表示这是一个切面
@Component 表示这是一个bean,由Spring进行管理
@Around(value = "execution(* com.service.ProductService.*(..))") 表示对com.service.ProductService 这个类中的所有方法进行切面操作
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<context:component-scan base-package="com.aspect"/>
<context:component-scan base-package="com.service"/>
<aop:aspectj-autoproxy/>

上一篇 下一篇

猜你喜欢

热点阅读