Spring assembles beans based on annotations, and only uses annotations for programming without using configuration files

Spring assembles beans based on annotations

Since JDK 5.0, Java has provided Annotation
Spring does not use annotations to assemble beans by default, so you need to add context: annotation config / in the configuration file to enable annotations.

Common annotations in Spring are as follows

  • @Component

This annotation can be used to describe beans in Spring, but it is a generalized concept that represents only one component (Bean) and can act at any level. When using, you only need to mark the annotation on the corresponding class.

  • @Repository

The class used to identify the data access layer (DAO layer) as a Bean in Spring has the same function as @ Component.

  • 3@Service

It usually acts on the business layer (Service layer) to identify the class of the business layer as a Bean in Spring, and its function is the same as @ Component.

  • @Controller

It usually acts on the control layer (such as the Action of struts 2 and the Controller of Spring MVC). It is used to identify the class of the control layer as a Bean in Spring, and its function is the same as @ Component.

  • @Autowired

It can be applied to Bean's attribute variables, attribute setter methods, non setter methods and constructors, and cooperate with the corresponding annotation processor to complete the automatic configuration of Bean. By default, it is assembled according to the type of Bean.

  • @Resource

The function is the same as that of Autowired, except that @ Autowired is assembled according to the Bean type by default, while @ Resource is assembled according to the Bean instance name by default.

@There are two important attributes in a Resource: name and type.

Spring resolves the name attribute to the instance name of the Bean, and the type attribute to the instance type of the Bean. If the name attribute is specified, the assembly is performed by the instance name; If the type attribute is specified, the assembly is performed by Bean type. If none is specified, assemble according to the Bean instance name first. If it cannot match, assemble according to the Bean type again; If none of them can match, a NoSuchBeanDefinitionException is thrown.

  • @Qualifier

When used with @ Autowired annotation, the default assembly by Bean type will be modified to assembly by Bean instance name, which is specified by the parameter of @ Qualifier annotation.

be careful:
resource is equivalent to the combination of autowired and qualifier

Example:

  • spring 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:context="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">


    <!-- Benchmark package for annotation scanning -->
    <!--use context Namespace, notification spring Scan the specified directory for annotation parsing -->
    <context:component-scan base-package="com.ljw"></context:component-scan>
</beans>
  • Define three-tier classes: action, service and dao

- action

@Controller
public class UsersAction {
    @Resource(name = "us")
    private UsersService usersService;
    public void add() {
        System.out.println("action Add method in");
        usersService.add();
    }

**- service **

@Service(value = "us")
public class UsersService {
    @Autowired
    //You need to specify the injected interface implementation
    @Qualifier("usersDaoImpl")
    private UsersDao usersDao;
    public int add(){
        System.out.println("service Add method in");
        return usersDao.add();
    }

-Two implementations of Dao

be careful:
If there is only one implementation of the interface, it does not need to be specified

Interface:

public interface UsersDao {
    public int add();
}
  • Implementation 1
@Repository
public class UsersDaoImpl implements UsersDao {
    @Override
    public int add(){
        System.out.println("dao Add method");
        return 1;
    }
  • Implementation 2
@Repository
public class UsersDaoImpl2 implements UsersDao {
    @Override
    public int add(){
        System.out.println("dao Add method 2");
        return 2;
    }

Annotations under the basic package can be ignored or only contain certain annotations

    <!-- Benchmark package for annotation scanning -->
    <context:component-scan base-package="com.ljw" use-default-filters="false">
        <!--Some annotations can be set to be ignored-->
        <!--ignore action Notes for-->
<!--        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
        <!--Or just a comment
            This property needs to be set use-default-filters="false"
        -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
  • test
    @Test
    public void test07(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
        //Default initial lowercase id name
        //@The Repository uses this annotation
        UsersDao usersDao = context.getBean(UsersDaoImpl2.class);
        System.out.println(usersDao);
        usersDao.add();
        //@Service uses this annotation to alias @ Service(value = "us")
        UsersService usersService = context.getBean("us", UsersService.class);
        System.out.println(usersService);
        //The service will call Dao's method to inject the attribute @ Autowired, which is assembled by type by default
        usersService.add();
        //@The Controller uses this annotation
        UsersAction usersAction = context.getBean("usersAction", UsersAction.class);
        System.out.println(usersAction);
        //action will call the method of service, so attribute injection is required
        // @Resource(name = "us") specifies the implementation of the interface
        // private UsersService usersService;
        usersAction.add();
    }

You don't need a configuration file. Create your own SpringConfig class

Add annotations to the custom class and call AnnotationConfigApplicationContext to get the ApplicationContext

  • Configuration class
@Configuration
@ComponentScan(basePackages = {"com.ljw"})
public class SpringConfig {
}
  • Injection properties
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class Users {
//Assign values to general attributes
    @Value("1")
    private Integer id;
    @Value("zhangsan")
    private String name;
}
  • test
@Test
    public void test08(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Users users = context.getBean("users", Users.class);
        System.out.println(users.getId() + "\t" + users.getName());
        UsersDao usersDao = context.getBean(UsersDaoImpl.class);
        usersDao.add();
        UsersService usersService = context.getBean(UsersService.class);
        usersService.add();
        //Normally call annotated classes and methods
    }

Tags: Java Spring mvc

Posted on Wed, 15 Sep 2021 01:51:58 -0400 by Blade280891