Spring ~ store beans with annotations (class annotations, method annotations)


We learned earlier that if you want to store an object in spring, you need the following steps:
1. Create a maven file 2.
Introduce the spring dependency package in 3. Create a configuration xml file to store the bean object 4. In the test class , get the bean object to call through the context object pom.xml

Every time you want to store a bean object, you need to modify it in the configured xml file, which is very troublesome. In order to make it easier to store and read objects and operate directly in the code, spring provides annotations to solve this problem.

The core of Spring is IOC, which is to initialize and load the bean object into the container, and load the bean into the container in two ways: configure the XML file or use Spring annotations . The latter is introduced here, which is easy to operate, easy to manage, and can improve development efficiency.

How to store spring more easily

1. Create a mavenfile
2. Add springthe core package
3. Configure the xml file and configure the scan path in the file
4. Use annotations to read and store directly in the code

In the past, when storing a bean object, it was necessary to manually create a bean in the configuration file. Here, a scan path is directly configured, and all objects that need to be stored are placed in this directory. When we use annotations to identify the class in the code , spring will automatically scan this path and automatically add the corresponding object to the spring framework.

Configure scan path

Before using annotations, we need to configure the scan path, put all objects directly under this path, and spring will automatically scan the corresponding beans and add them to the framework.

Create an xml configuration file:

<?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:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="model"></content:component-scan>
</beans>

The path where the object is stored is written in the base-package attribute here, which is placed under the model package.
insert image description here
Once configured, annotations can be used.

There are many categories of annotations, class annotations, method annotations, transaction module annotations, springMVC annotations, etc., which will be introduced later. Broadly, they can be divided into two categories: one is to register beans, and the other is to use beans. Simple and commonly used annotations, these annotations can be divided into the first category - registered Bean.
Class annotations: @Configuration, @Controller, @Servie, @Repository, @Component.
Method annotation: @Bean.

Introduction to class annotations:

Q: How does Spring know which Javal classes to register with the container?
Answer: Use configuration files or annotations to identify the Java classes that need to be processed.

Class annotations can also be called component class annotations , that is, some classes are used as components.

@Component : Identifies a common bean class
@Controller : Identifies a controller component class, which is generally used in classes that control front-end and back-end interactions for data verification.
@Service : Identifies a business logic component class for data assembly.
@Repository : Identifies a DAO component class, that is, a data access layer component, which is used to access data, such as connecting to a database, to perform additions, deletions, and changes.
@Configuration : Identifies a class as the configuration class for loading spring. The role of this class is to configure spring and start the spring container.

The relationship between class annotations

insert image description here
The four annotations @Component, @Controller, @Service, and @Repository are actually a class of annotations, with the same functions and the same usage. The difference is to identify the component type of the current class, so that programmers can quickly understand the role of the current class.

@Component can replace @Controller, @Service, @Repository , because these three annotations are annotated by @Component, which can be logically understood as a subclass of Component.

As shown below:
Controller, Service, and Repository are all marked by Component.
insert image description hereinsert image description here
insert image description here
insert image description here

Example:

@Controller

UserController class as bean:

package model;

import org.springframework.stereotype.Controller;

@Controller //将当前类储存到Spring,标识此类为控制交互层
public class UserController {
    
    
    public void firstUseController(String name){
    
    
        System.out.println("Hi,Controller:"+name);
    }
}

In the test class use:

import model.HelloApplicationContext;
import model.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
      ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
     UserController userController=(UserController) context.getBean("userController");
     userController.firstUseController("Hello!");
    }
}

output:

Hi,Controller:Hello!

@Served

UserService as bean:

package model;

import org.springframework.stereotype.Service;

@Service //将此类储存到String中,这个类中可以进行数据组装
public class UserService {
    
    
    public void firstUseService(String name){
    
    
        System.out.println("Hi,Service:"+name);
    }
}

In the test class use:

import model.HelloApplicationContext;
import model.UserController;
import model.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
      ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
      UserService userService=(UserService) context.getBean("userService");
      userService.firstUseService("Hello!");
    }
}

output:

Hi,Service:Hello!

@Repository

package model;

import org.springframework.stereotype.Repository;

@Repository//将此类储存到String中,标识此类是数据访问组件
public class UserRepository {
    
    
    public void firstUseRepository(String name){
    
    
        System.out.println("Hi,Repository:"+name);
    }
}

In the test class use:

import model.HelloApplicationContext;
import model.UserController;
import model.UserRepository;
import model.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
      ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
      UserRepository userRepository=(UserRepository) context.getBean("userRepository");
      userRepository.firstUseRepository("Hello!");
    }
}

output:

Hi,Repository:Hello!

@Component

package model;

import org.springframework.stereotype.Component;

@Component 
public class UserComponent {
    
    
    public void firstUseComponent(String name){
    
    
        System.out.println("Hi,Component:"+name);
    }
}

In the test class use:

import model.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
      ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
      UserComponent userComponent=(UserComponent) context.getBean("userComponent");
      userComponent.firstUseComponent("Hello!");
    }
}

output:

Hi,Component:Hello!

be careful:

  • The annotated Java class will be stored in spring as a Bean object. The default name of this object is the first letter of the class name in lowercase, and the rest remains unchanged.
    insert image description here
  • @Service can also customize the bean name, but it must be unique .
  • Try to use the corresponding component annotation to replace @Component, because in future Spring versions, @Controller, @Service, @Repository may carry more semantics .

method annotation

Method annotation: @Bean. Annotation before the method, the function is to make this method generate a Bean object, and then this Bean object is handed over to the container for management . This method will only be called once by spring, and then put this object into its own IOC container.

package model;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class UserBean {
    
    
    private String name;
    private int Id;
    private int age;
    public void setName(String name) {
    
    
        this.name = name;
    }
    public void setId(int id) {
    
    
        Id = id;
    }
    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "UserBean{" +
                "name='" + name + '\'' +
                ", Id=" + Id +
                ", age=" + age +
                '}';
    }

    @Bean
    public UserBean users(){
    
    
        UserBean user=new UserBean();
        user.setName("张三");
        user.setId(01);
        user.setAge(18);
        return user;
    }
}

Run in the test class:

import model.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.jws.soap.SOAPBinding;

public class App {
    
    
    public static void main(String[] args) {
    
    
        //1.获取上下文对象
      ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
      //2.获取spring中存入的bean对象,id默认是类名首字母小写,其余不变
       UserBean user=(UserBean)context.getBean("users");
       //3.调用方法
        System.out.println(user.toString());
    }
}

The results are as follows:

UserBean{
    
    name='张三', Id=1, age=18}

Note: Spring scans classes by default. If you use method annotations @Bean, you need to use them with class annotations @Componentor @Configurationuse them together. Otherwise, spring cannot scan this method, and you cannot store the method returned object in spring.

Renaming
When using @Bean, we can rename the method and create multiple names for the method at the same time:


    @Bean(name={
    
    "u1","us1"})
    public UserBean users(){
    
    
        UserBean user=new UserBean();
        user.setName("张三");
        user.setId(01);
        user.setAge(18);
        return user;
    }

When multiple names are created, the original method name is invalid, and we can use renaming to get the bean object.
insert image description here

Guess you like

Origin blog.csdn.net/Merciful_Lion/article/details/124018334