Table of Contents
1. Use annotations to configure spring
1. Steps
Home Java javaTutorial Detailed introduction to using annotations to configure spring

Detailed introduction to using annotations to configure spring

Jun 30, 2017 am 09:53 AM
javaee Configuration

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The perfect combination of PyCharm and PyTorch: detailed installation and configuration steps The perfect combination of PyCharm and PyTorch: detailed installation and configuration steps Feb 21, 2024 pm 12:00 PM

PyCharm is a powerful integrated development environment (IDE), and PyTorch is a popular open source framework in the field of deep learning. In the field of machine learning and deep learning, using PyCharm and PyTorch for development can greatly improve development efficiency and code quality. This article will introduce in detail how to install and configure PyTorch in PyCharm, and attach specific code examples to help readers better utilize the powerful functions of these two. Step 1: Install PyCharm and Python

The working principle and configuration method of GDM in Linux system The working principle and configuration method of GDM in Linux system Mar 01, 2024 pm 06:36 PM

Title: The working principle and configuration method of GDM in Linux systems In Linux operating systems, GDM (GNOMEDisplayManager) is a common display manager used to control graphical user interface (GUI) login and user session management. This article will introduce the working principle and configuration method of GDM, as well as provide specific code examples. 1. Working principle of GDM GDM is the display manager in the GNOME desktop environment. It is responsible for starting the X server and providing the login interface. The user enters

How to set up Git configuration in PyCharm How to set up Git configuration in PyCharm Feb 20, 2024 am 09:47 AM

Title: How to correctly configure Git in PyCharm In modern software development, the version control system is a very important tool, and Git, as one of the popular version control systems, provides developers with powerful functions and flexible operations. As a powerful Python integrated development environment, PyCharm comes with support for Git, allowing developers to manage code versions more conveniently. This article will introduce how to correctly configure Git in PyCharm to facilitate better development during the development process.

Understand Linux Bashrc: functions, configuration and usage Understand Linux Bashrc: functions, configuration and usage Mar 20, 2024 pm 03:30 PM

Understanding Linux Bashrc: Function, Configuration and Usage In Linux systems, Bashrc (BourneAgainShellruncommands) is a very important configuration file, which contains various commands and settings that are automatically run when the system starts. The Bashrc file is usually located in the user's home directory and is a hidden file. Its function is to customize the Bashshell environment for the user. 1. Bashrc function setting environment

Simple and easy-to-understand PyCharm configuration Git tutorial Simple and easy-to-understand PyCharm configuration Git tutorial Feb 20, 2024 am 08:28 AM

PyCharm is a commonly used integrated development environment (IDE). In daily development, using Git to manage code is essential. This article will introduce how to configure Git in PyCharm and use Git for code management, with specific code examples. Step 1: Install Git First, make sure Git is installed on your computer. If it is not installed, you can go to [Git official website](https://git-scm.com/) to download and install the latest version of Git

How to configure workgroup in win11 system How to configure workgroup in win11 system Feb 22, 2024 pm 09:50 PM

How to configure a workgroup in Win11 A workgroup is a way to connect multiple computers in a local area network, which allows files, printers, and other resources to be shared between computers. In Win11 system, configuring a workgroup is very simple, just follow the steps below. Step 1: Open the "Settings" application. First, click the "Start" button of the Win11 system, and then select the "Settings" application in the pop-up menu. You can also use the shortcut "Win+I" to open "Settings". Step 2: Select "System" In the Settings app, you will see multiple options. Please click the "System" option to enter the system settings page. Step 3: Select "About" In the "System" settings page, you will see multiple sub-options. Please click

How to configure and install FTPS in Linux system How to configure and install FTPS in Linux system Mar 20, 2024 pm 02:03 PM

Title: How to configure and install FTPS in Linux system, specific code examples are required. In Linux system, FTPS is a secure file transfer protocol. Compared with FTP, FTPS encrypts the transmitted data through TLS/SSL protocol, which improves Security of data transmission. In this article, we will introduce how to configure and install FTPS in a Linux system and provide specific code examples. Step 1: Install vsftpd Open the terminal and enter the following command to install vsftpd: sudo

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

See all articles