SpringIoc study notes (annotation method)

   We know that the SpringIOC container creates objects through xml configuration bean tags. If there are multiple classes, we need to write a lot of bean tags in the xml configuration file. Is there any other way to create objects? Of course, with that is SpringIOC's annotation development, we only need to add annotations to the required classes. Let's talk about common annotations first, and then give examples.
1, @Component annotation

1. @Component Annotation:
   Function: modify a class and give this class to the Spring container for management, which is equivalent to adding a bean tag in the xml file.
   Attribute: value: used to specify the id of the bean. When we don't write, its default value is the current class name, and the first letter is changed to lowercase.
This annotation has three derivative annotations (same functions), which are also modified classes:
   @Controller: Generally used for presentation layer annotations.
   @Service: Generally used for service layer annotations.
   @Repository: Generally used for data access layer.

Example: Create a maven project, as shown below:
Insert picture description here
UserService interface and interface implementation class:

/*
* 保存用户接口
* */
public interface UserService {
    
    
    /*
    * 保存用户
    * */
    void saveUser();
}

/*
*@Component注解
* 作用:把资源让spring来管理。相当于在xml中配置一个 bean。<bean id="" class="" scope=""></bean>
* 属性:
*   value:指定bean的id。如果不指定value属性,默认bean的id是当前类的类名。首字母小写。
* */
@Component
public class UserServiceImpl implements UserService {
    
    
    public void saveUser() {
    
    
        System.out.println("saveUser方法执行了");
    }
}

bean.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--开启IOC的注解开发包扫描-->
    <context:component-scan base-package="com.zy.service"></context:component-scan>
</beans>

pom file:

<dependencies>
        <!--引入spring核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
</dependencies>

Test category:

public class TestIocAnno {
    
    
    public static void main(String[] args) {
    
    
        //加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //根据bean标签的id获取实例
        UserService bean = (UserService) context.getBean("userServiceImpl");
        //调用方法
        bean.saveUser();
    }
}

Operation result:
Insert picture description here
2, @Autowired annotation

2. @Autowired annotation
   function: automatically inject according to type. When using annotation to inject properties, the set method can be omitted. It can only inject other bean types. When there are multiple types matching, use the object variable name to be injected as the bean id, look it up in the spring container, and it can be injected successfully if found. Report an error if not found.

We add a dao layer interface and implementation class to this maven, and inject the dao layer into the service layer.

public interface UserDao {
    
    
    /*
     * 保存用户
     * */
    void saveUser();
}
/*
* dao接口实现类
* */
@Component
public class UserDaoImpl implements UserDao {
    
    
    public void saveUser() {
    
    
        System.out.println("dao保存用户成功...");
    }
}

Modify the UserServiceImpl code as follows:

@Component
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserDaoImpl userDao;

    public void saveUser() {
    
    
        //调用dao层的方法
        userDao.saveUser();
        System.out.println("saveUser方法执行了");
    }
}

The results of running the test class are as follows:
Insert picture description here
If there are two objects of the same type when we use the @Autowired annotation, the running result will report an error, for example, the following code:

@Repository(value = "userDao1")
public class UserDaoImpl implements UserDao {
    
    
    public void saveUser() {
    
    
        System.out.println("dao保存用户成功111...");
    }
}
@Repository(value = "userDao2")
public class UserDaoImpl2 implements UserDao {
    
    
    public void saveUser() {
    
    
        System.out.println("dao保存用户成功222...");
    }
}

The results of running the test class are as follows:
Insert picture description hereHow to solve it, we need to use another annotation to work with @Autowired.
3. @Qualifier annotation

@Qualifier Annotation:
   Function: On the basis of automatic injection according to the type, injection according to the id of the Bean. It cannot be used independently when injecting fields, it must be used with @Autowire, but when injecting method parameters, it can be used independently.
   Attribute: value: specifies the id of the bean.

Add this annotation to the service layer implementation class and determine which one to inject through the value attribute.

@Component
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    @Qualifier(value = "userDao2")
    private UserDao userDao;

    public void saveUser() {
    
    
        //调用dao层的方法
        userDao.saveUser();
        System.out.println("saveUser方法执行了");
    }
}

Then run the test class:
Insert picture description here
4. @Resource annotation
   If we don't want to use @Autowired and @Qualifier annotations together, we can use @Resource annotation, which is injected directly according to the id of the bean. It can only inject other bean types, and it also has a name attribute.

@Component
public class UserServiceImpl implements UserService {
    
    

//    @Autowired
//    @Qualifier(value = "userDao2")
    @Resource(name = "userDao1")
    private UserDao userDao;

    public void saveUser() {
    
    
        //调用dao层的方法
        userDao.saveUser();
        System.out.println("saveUser方法执行了");
    }
}

4. @Value annotation:
   The function of this annotation is to inject basic data type and String type data, attribute: value: used to specify the value. You can use the SpEL expression in spring, ${expression}
5, @Scope annotation: role: specify the scope of the bean. Attribute: value: the value of the specified range. Value: singleton prototype, request, session, globalsession.

@Service
@Scope(value = "singleton")
public class UserServiceImpl implements UserService {
    
    ......}

6, @PostConstruct annotation: role: used to specify the initialization method

@Service
@Scope(value = "singleton")
public class UserServiceImpl implements UserService {
    
    
//    @Autowired
//    @Qualifier(value = "userDao2")
    @Resource(name = "userDao1")
    private UserDao userDao;

    @PostConstruct
    public void init(){
    
    
        System.out.println("初始化成功");
    }
    @PreDestroy
    public void destroy(){
    
    
        System.out.println("销毁成功");
    }
    public void saveUser() {
    
    
        //调用dao层的方法
        userDao.saveUser();
        System.out.println("saveUser方法执行了");
    }
}

7. @PreDestroy Note: Function: Used to specify the destruction method.

@Service
@Scope(value = "singleton")
public class UserServiceImpl implements UserService {
    
    
//    @Autowired
//    @Qualifier(value = "userDao2")
    @Resource(name = "userDao1")
    private UserDao userDao;
    @PostConstruct
    public void init(){
    
    
        System.out.println("初始化成功");
    }
    @PreDestroy
    public void destroy(){
    
    
        System.out.println("销毁成功");
    }
    public void saveUser() {
    
    
        //调用dao层的方法
        userDao.saveUser();
        System.out.println("saveUser方法执行了");
    }
}

Come on, boy

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/111238966