Home > Java > javaTutorial > Detailed introduction to using annotations to configure spring

Detailed introduction to using annotations to configure spring

零下一度
Release: 2017-06-30 09:53:47
Original
1841 people have browsed it

1. Use annotations to configure spring

1. Steps

1.1 Guide package 4+2+spring-aop

4 represents:

## 2 represents:

Log package: com.springsource.org.apache.commons.logging-1.1.1.jar

Optional: com.springsource. org.apache.log4j-1.2.15.jar (the old version needs to be imported, and the import can guarantee that it will run)

  1.2 Introduce a new namespace (constraint) to the main configuration file

1.3 Enable the use of annotations instead of configuration files

1.4 Use annotations in classes to complete configuration

2. Register the object to the container

//<bean name="user" class="cn.itcast.bean.User"  />//@Component("user")//    @Service("user") // service层//    @Controller("user") // web层@Repository("user")// dao层
Copy after login
3. Modify Scope of object

//指定对象的作用范围@Scope(scopeName="singleton")
Copy after login
4. Value type injection

Field assignment through reflection destroys encapsulation:

    @Value("tom")    private String name;
Copy after login
Assignment through the set method is recommended.:

    @Value("tom")    public void setName(String name) {this.name = name;
    }
Copy after login
5. Reference type injection

    //@Autowired //自动装配//问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.//@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象private Car car;
Copy after login

Recommended method:

    @Resource(name="car")//手动注入,指定注入哪个名称的对象private Car car;
Copy after login
6. Initialization|Destruction method

    @PostConstruct //在对象被创建后调用.init-methodpublic void init(){
        System.out.println("我是初始化方法!");
    }
    @PreDestroy //在销毁之前调用.destory-methodpublic void destory(){
        System.out.println("我是销毁方法!");
    }
Copy after login
2. STS plug-in

1 .Manual installation of plug-ins (low success rate)

 

 Step 1:

 

 Step 2:

 

 Step 3:

 

 2. Directly use spring to install the plug-in eclipse

 

3. Spring and junit integration test

1. Guide package 4+2+aop+test

2. Configuration annotation

//帮我们创建容器@RunWith(SpringJUnit4ClassRunner.class)//指定创建容器时使用哪个配置文件@ContextConfiguration("classpath:applicationContext.xml")public class Demo {//将名为user的对象注入到u变量中@Resource(name="user")private User u;
Copy after login

 3. Test
    @Testpublic void fun1(){
        
        System.out.println(u);
        
    }
Copy after login

4. Aop in spring

 1.Introduction to aop thinking

2. AOP concept in spring

3. The principle of spring implementing aop

3.1 Dynamic proxy (priority)

The proxy object must implement the interface to generate a proxy object. If there is no interface, dynamic proxy technology cannot be used

  3.2 cglib proxy (no interface)

Third-party proxy technology, cglib proxy. Proxy can be generated for any class. The principle of proxy is to inherit the proxy for the target object. If the target object is final modified. Then This class cannot be proxied by cglib.

 4.aop noun learning

 

5. Aop demonstration in spring

1. Steps (xml configuration)

1.1 Guide package 4+2

Spring’s aop package:

spring-aspects-4.2.4.RELEASE.jar

  spring-aop-4.2.4.RELEASE.jar

   Spring requires a third-party aop package:

   com.springsource.org.aopalliance-1.0.0.jar

 com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

 1.2 Prepare the target object

public class UserServiceImpl implements UserService {
    @Overridepublic void save() {
        System.out.println("保存用户!");//int i = 1/0;    }
    @Overridepublic void delete() {
        System.out.println("删除用户!");
    }
    @Overridepublic void update() {
        System.out.println("更新用户!");
    }
    @Overridepublic void find() {
        System.out.println("查找用户!");
    }
}
Copy after login

 1.3 Prepare the notification
//通知类public class MyAdvice {    //前置通知    
//        |-目标方法运行之前调用//后置通知(如果出现异常不会调用)//        |-在目标方法运行之后调用//环绕通知//        |-在目标方法之前和之后都调用//异常拦截通知//        |-如果出现异常,就会调用//后置通知(无论是否出现 异常都会调用)//        |-在目标方法运行之后调用//----------------------------------------------------------------//前置通知public void before(){
        System.out.println("这是前置通知!!");
    }//后置通知public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }//环绕通知public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法System.out.println("这是环绕通知之后的部分!!");return proceed;
    }//异常通知public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }//后置通知public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}
Copy after login

  1.4 Configure weaving and weave the notification into the target object
<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/context  http://www.springframework.org/schema/aop  "><!-- 准备工作: 导入aop(约束)命名空间 --><!-- 1.配置目标对象 --><bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean><!-- 2.配置通知对象 --><bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" ></bean><!-- 3.配置将通知织入目标对象 --><aop:config><!-- 配置切入点 
            public void cn.itcast.service.UserServiceImpl.save() 
            void cn.itcast.service.UserServiceImpl.save()
            * cn.itcast.service.UserServiceImpl.save()
            * cn.itcast.service.UserServiceImpl.*()
            
            * cn.itcast.service.*ServiceImpl.*(..)
            * cn.itcast.service..*ServiceImpl.*(..)--><aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/><aop:aspect ref="myAdvice" ><!-- 指定名为before方法作为前置通知 --><aop:before method="before" pointcut-ref="pc" /><!-- 后置 --><aop:after-returning method="afterReturning" pointcut-ref="pc" /><!-- 环绕通知 --><aop:around method="around" pointcut-ref="pc" /><!-- 异常拦截通知 --><aop:after-throwing method="afterException" pointcut-ref="pc"/><!-- 后置 --><aop:after method="after" pointcut-ref="pc"/></aop:aspect></aop:config></beans>
Copy after login

 2. Steps (annotation configuration)
  Previous Steps 1, 2, and 3 are the same as the xml configuration

2.4 Configuration is woven into the target object

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/context  http://www.springframework.org/schema/aop  "><!-- 准备工作: 导入aop(约束)命名空间 --><!-- 1.配置目标对象 --><bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean><!-- 2.配置通知对象 --><bean name="myAdvice" class="cn.itcast.e_annotationaop.MyAdvice" ></bean><!-- 3.开启使用注解完成织入 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
Copy after login

Notification class:
//通知类@Aspect//表示该类是一个通知类public class MyAdvice {
    @Pointcut("execution(* cn.itcast.service.*ServiceImpl.*(..))")public void pc(){}//前置通知//指定该方法是前置通知,并制定切入点@Before("MyAdvice.pc()")public void before(){
        System.out.println("这是前置通知!!");
    }//后置通知@AfterReturning("execution(* cn.itcast.service.*ServiceImpl.*(..))")public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }//环绕通知@Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法System.out.println("这是环绕通知之后的部分!!");return proceed;
    }//异常通知@AfterThrowing("execution(* cn.itcast.service.*ServiceImpl.*(..))")public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }//后置通知@After("execution(* cn.itcast.service.*ServiceImpl.*(..))")public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}
Copy after login

The above is the detailed content of Detailed introduction to using annotations to configure spring. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template