Spring-based annotation management bean and full annotation development

spring overview

Spring definition

  • Spring is a mainstream Java EE lightweight open source framework, which aims to simplify the development difficulty and development cycle of Java enterprise-level references. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. In addition to providing its own functions, the Spring framework also provides the ability to integrate other technologies and frameworks.
  • Spring has been favored since its birth, and has been regarded as the first choice for Java enterprise application development by developers. Today, Spring has become synonymous with Java EE and the de facto standard for building Java EE applications.
  • Since the official release of Spring 1.0 in April 2004, Spring has entered the sixth major version, namely Spring 6. This course adopts the official version of Spring 5.3.24. Spring6 version supports JDK17
    insert image description here

Spring core

Spring refers to the Spring Framework, usually we call it the Spring Framework. The Spring framework is a layered, one-stop solution framework for aspect-oriented Java applications. It is the core and foundation of the Spring technology stack and was created to solve the complexity of enterprise-level reference development.

  • Spring has two core modules: IoC and AOP.
  • Ioc: shorthand for Inverse of Control, which is inversion of control, which refers to handing over the created object to Spring for management.
  • OP: Short for Aspect Oriented Programming, object-oriented programming. AOP is used to encapsulate the public behavior of multiple classes, and encapsulate the logic that is not related to the business but is commonly called by the business modules, so as to reduce the duplication of code in the system and reduce the coupling between modules. In addition, AOP also solves some system-level problems, such as logs, transactions, permissions, etc.

Features of Spring Framework

  • Inversion of control: IoC, inverting the direction of resource acquisition; turning the resources created by oneself and requesting resources from the environment into the environment to prepare the resources, and we enjoy resource injection.
  • Aspect-oriented programming: AOP, which enhances code functions without modifying source code.
  • Container: Spring IoC is a container because it contains and manages the life cycle of component objects; components enjoy containerized management, which shields programmers from a large number of details in the component creation process, greatly reduces the threshold for use, and greatly improves development efficiency.
  • One-stop shop: On the basis of IOC and AOP, various enterprise application open source frameworks and excellent third-party libraries can be integrated, and the projects under Spring have covered a wide range of fields, and many functional requirements can be found in the Spring Framework. Basically, all of them are implemented using Spring.

Manage beans based on annotations

  • Starting from Java5, Java has added support for annotations (Annotation), which is a special mark in the code, which can be read during compilation, class loading and runtime, and perform corresponding processing. Developers can embed supplementary information in source code without changing the original code and logic through annotations.
  • Spring has provided comprehensive support for annotation technology since version 2.5. We can use annotations to realize automatic assembly and simplify Spring's xml configuration.
  • Spring implements automatic assembly through annotations:
  1. Introduce dependencies
  2. Turn on component scanning
  3. Define beans using annotations
  4. dependency injection

rely

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.24</version>
    </dependency>
</dependencies>

Turn on component scanning

  • Spring does not use annotations to assemble beans by default, so you need to enable the automatic scanning function of Spring Beans through the context:component-scan element in Spring's xml configuration. After enabling this function, Spring will automatically scan the specified package (base-package attribute setting) and all classes under its subpackages. If the @Component annotation is used on the class, the class will be assembled into the container.
  • Create a spring configuration file bean.xml in the resources directory
<?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:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd

       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 2.开启组件扫描,让spring可以通过注解方式实现bean管理,包括创建对象、属性注入 -->
    <!-- base-package:扫描哪个包中的注解,在com.text的包或者子包中建了类,在
     类上、属性上、方法上加了spring的@Component注解,这里就能扫描到-->
    <context:component-scan base-package="com.text.spring"></context:component-scan>  
</beans>

Define beans using annotations

Spring provides the following multiple annotations, which can be directly annotated on java classes to define them as Spring Beans.

annotation illustrate
@Component This annotation is used to describe the Bean in Spring. It is a generalized concept that only identifies a component (Bean) in the container, and can be used at any level, such as the Service layer, Dao layer, etc. When using it, you only need to use the Annotations can be marked on the corresponding class.
@Respository The classes annotated for the data access layer (Dao layer) are identified as beans in Spring, and have the same function as @Component.
@Service This annotation usually acts on the business layer (Service layer), and is used to identify the class of the business layer as a bean in Spring, and its function is the same as that of @Component.
@Controller This annotation usually acts on the control layer (such as the Controller of SpringMVC), and is used to identify the class of the control layer as a bean in Spring, and its function is the same as that of @Component.

case:

// value可以不写,默认为类名首字母小写
//@Component(value = "user")  // <bean id="user" class="xxx">
//@Repository
//@Service
@Controller
public class User {
    
    

}
  • test
public class TestUser {
    
    
    @Test
    public void testUser(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        User user = context.getBean("user", User.class);
        System.out.println("user = " + user);
    }
}

@Autowired injection

  • Using the @Autowired annotation alone, the default is to assemble according to the type (byType)
  • The @Autowired annotation has a required attribute, the default value is true, which means that the injected Bean must exist during injection, and an error will be reported if it does not exist. If the required attribute is set to false, it doesn’t matter whether the injected Bean exists or not. If it exists, it will be injected, and if it does not exist, no error will be reported.

attribute injection

  • Controller layer controller.UserController
public class UserController {
    
    
    private UserService userService;
    
    public void addController(){
    
    
        System.out.println("controller is running...");
        userService.addService();
    }
}
  • Service layer service.UserService interface
public interface UserService {
    
    
    public void addService();
}
  • The implementation class of the service layer service.UserServiceImpl interface
public class UserServiceImpl implements UserService {
    
    
    @Override
    public void addService() {
    
    
        System.out.println("service is running...");
    }
}
  • Add @Controller annotation and @Service annotation to UserController and UserSerivceImpl
  • Inject UserServiceImpl in UserController
@Controller
public class UserController {
    
    
    // 注入service
    // 第一种方式:属性注入
    @Autowired // 根据类型找到对象,完成注入
    private UserService userService;
}
  • Test class test autowired.TestUserController
public class TestUserController {
    
    
    @Test
    public void testUserController(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserController controller = context.getBean(UserController.class);
        controller.addController();
    }
}

set injection

  • Modify the UserController class
// 第三种方式:构造方法注入
private UserService userService;

@Autowired
public UserController(UserService userService) {
    
    
    this.userService = userService;
}

katasanjo injection

  • Modify the UserController class
// 第四种方式:形参注入
private UserService userService;

public UserController(@Autowired UserService userService) {
    
    
    this.userService = userService;
}

Only one constructor, no annotations

  • Modify the UserController class
// 第五种方式:只有一个有参数构造函数,无注解
private UserService userService;

public UserController(UserService userService) {
    
    
    this.userService = userService;
}

Combination of @Autowire annotation and @Qualifier annotation

  • Create another implementation class service.UserServiceImpl2 of the UserService interface
@Service
public class UserServiceImpl2 implements UserService{
    
    
    @Override
    public void addService() {
    
    
        System.out.println("service2 is running...");
    }
}
  • The test found an error

    Because UserService has two implementation classes, and the @Autowired annotation is positioned according to byType, two implementation classes are found

  • Solution: Modify UserController (using two annotations)

// 1.第六种方式:根据类型和名称一起注入
@Autowired
@Qualifier(value = "userServiceImpl2")  // 类名首字母小写
private UserService userService;

// 2.将构造函数注释

@Resource injection

The @Resource annotation can also complete attribute injection. The difference between it and the @Autowired annotation is as follows

  • The @Resource annotation is in the JDK extension package, which means it is part of the JDK. So the explanation is a standard annotation, which is more general, while the @Autowired annotation is the Spring framework's own.
  • The @Resource annotation is assembled byName by name by default. When the name is not specified, the attribute name is used as the name. If the name cannot be found, it will automatically start the assembly byType by type. The @Autowired annotation is assembled byType by type by default. If you want to match by name, you need to use it with the @Qualifier annotation.
  • @Resource annotation is used on properties and setter methods
  • The @Autowired annotation is used on properties, setter methods, construction methods, and construction method parameters.
    the case
  • Create a package resource under the project, as before, create two packages of controller and service, and create the UserController class and UserService interface, as well as the implementation class UserServiceImpl of the interface
  • Modify UserController
@Controller("myUserController")
public class UserController {
    
    
    // 根据名称进行注入
    @Resource(name="myUserService")
    private UserService userService;

    public void add(){
    
    
        System.out.println("controller...");
        userService.add();
    }
}
  • Modify ServiceControllerImpl1
@Service("myUserService")
public class UserServiceImpl implements UserService {
    
    
  1. Specify the name in @Resource, then assemble according to the name
  2. When no name is specified, it will be assembled according to the attribute name
  3. If the name is not specified and the attribute names are inconsistent, it will be assembled according to the type

Spring full annotation development

Full-annotation development is to no longer use the spring configuration file, and write a configuration class to replace the configuration file.

  • Create a package under the project: config, create a class SpringConfig
// 配置类
@Configuration
// 开启组件扫描
@ComponentScan("cn.tedu.spring")
public class SpringConfig {
    
    
}
  • Create a test class under resource for testing
public class TestUserControllerAnno {
    
    
    public static void main(String[] args) {
    
    
        // 加载配置类
        ApplicationContext context =
                new AnnotationConfigApplicationContext(SpringConfig.class);
        UserController controller = context.getBean(UserController.class);
        controller.add();
    }
}

Guess you like

Origin blog.csdn.net/m0_72568513/article/details/131977880