Spring 2 - annotation injection

1. @Component

1.1 definitions

Create an object, which is equivalent to the < bean > < / bean > function

1.2 create maven project

src/main/java/cn.kgc/...
src/main/resources/...
src/test/java/cn.kgc.test/...

1.3 pom.xml

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.20</version>
      <scope>provided</scope>
</dependency>

1.4 entity and add notes

@Getter
@Setter
@Component(value = "user")
public class User {
    private Integer id;
    private String name;
}

1.5 add applicationcontext.xml to the component scanner

<?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">
    <!--Declaration component scanner-->
    <context:component-scan base-package="cn.kgc.entity" />
</beans>

1.6 test Test01

@Test
public void test01(){
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) ac.getBean("user");
    System.out.println(user);
}

Result: cn.kgc.entity User@3ec300f1

1.7 expansion

The first extension (omitting value): @ Component("myUser")
The second extension (omitted, but can't be written casually by default): @ Component

2. @Repository

2.1 definitions

It is used on the persistence layer, and the method is on the implementation class of dao, indicating the creation of dao objects

2.2 UserMapper.java

public interface UserMapper {
    Integer addUser();
}

2.3 UserMapperImpl.java

@Repository(value = "userMapper")   
//When declaring the bean object of XXMapper, it is not recommended to omit the value in @ repository
public class UserMapperImpl implements UserMapper {
    @Override
    public Integer addUser() {
        System.out.println("Calling persistence layer methods...");
        return null;
    }
}

2.4 applicationContext.xml

 <!--Declaration component scanner-->
<context:component-scan base-package="cn.kgc.dao"/>
perhaps
<context:component-scan base-package="cn.kgc.entity;cn.kgc.dao" />
    <!--    cn.kgc It's OK, but it takes resources to sweep slowly-->

2.5 Test01

@Test
    public void test02(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) ac.getBean("userMapper");
        userMapper.addUser();
}

You can also write UserMapperImpl here, because the annotation is in this class,
But it doesn't make sense, so the interface can't be reflected.

Result: call the persistence layer method...

3. @ service (common)

3.1 definitions

It is used on the business layer and on the implementation class of the service,
Represents the creation of a service object, which can have some transaction functions

3.2 core code UserService

public interface UserService {
    public Integer addUser();
}

3.3 core code UserServiceImpl

import org.springframework.stereotype.Service;

@Service(value = "userService")
public class UserServiceImpl implements UserService {
    @Override
    public Integer addUser() {
        System.out.println("call UserService()method");
        return null;
    }
}

3.4 core code applicationContext.xml

<!--Declaration component scanner-->
<context:component-scan base-package="cn.kgc"/>

3.5 Test01

@Test
    public void test03(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.addUser();
}

Result: the UserService() method is called

4. @ controller (common)

4.1 definitions

It is used on the controller and placed on the controller to create the pre control object,
It can accept the parameters submitted by the user and display the processing results of the request

4.2 core code UserController

import org.springframework.stereotype.Controller;
@Controller(value = "userController")
public class UserController {
    public Integer addUser(){
       System.out.println("call userController of addUser()method");
        return 0;
    }
}

4.3 core code applicationContext.xml

<!--Declaration component scanner-->
<context:component-scan base-package="cn.kgc"/>

4.4 Test01.java

@Test
    public void test04(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = (UserController) ac.getBean("userController");
        userController.addUser();
}

Result: the addUser() method of userController is called

5. @Value

5.1 definitions

Assign values to simple type property objects

5.2 continue to write according to the @ Component example

>User and add comments

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "Aston")
    private String name;
//Note: @ Value is equivalent to the set() method. There is no need to define set()
}    

5.3 test Test01

@Test
    public void test05(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("id:" + user.getId() + "    name:" + user.getName());
}

Result: id:1 name: Aston

Above is the injection of simple types

Here are the injection reference types

6. @Autowired (common)

6.1 definitions

Assign a value to the reference type attribute (auto assemble Bean). byType auto injection is used by default.

6.2 create maven project

6. 3 pom

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.20</version>
      <scope>provided</scope>
</dependency>

6. 4 entity/User

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "You")
    private String name;
    @Autowired
    //It's based on the type, so it's OK to write the class name wrong
    private Role role;
}

6.4.2 entity/Role

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Setter
@Getter
@Component
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "Fresh student")
    private String rName;
}

6.4.3 expand entity/SonRole

@Component
public class SonRole extends Role{ }

entity/User

@Autowired
private SonRole sonRole;

test/.../TestSpring

System.out.println("name:" + user.getName() + "    rName:"+user.getSonRole().getRName());

6.5 add applicationcontext.xml to the component scanner

<!--Declaration component scanner-->
<context:component-scan base-package="cn.kgc" />

6. Test class TestSpring

    @Test
    public void demo01(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("name:" + user.getName() + "    rName:"+user.getRole().getRName());
}

Result: name: you, rName: fresh student

7. @ resource (common)

7.1 definition – > not spring annotation

Assign values to reference types. Spring provides support for JDK annotation @ Resource,
By default, it is injected by name. If injection by name fails, it is automatically injected by type

7.2 create maven project

7.3 pom.xml (omitted)

7. 4 entity/User

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "You")
    private String name;
    @Resource
private Role role;
}

7.4.1 entity/Role

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Setter
@Getter
@Component
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "Fresh student")
    private String rName;
}

7.5 add applicationcontext.xml to the component scanner

<context:component-scan base-package="cn.kgc.entity" />

7.6 test class TestSpring

public class TestSpring {
    @Test
    public void testdemo001(){
        String conf = "applicationContext.xml";
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        User user = (User) ac.getBean("user");
        System.out.println("name:" + user.getName() + "    rName:"+user.getRole().getRName());
    }
}

Result: name: you, rName: fresh student

As for the gang Jing, the name support is inconsistent with the class name,
The following resources can be output even if they are wrong.

8. @Resource expansion

8.1 create maven project

8.2 pom (omitted)

8.3 entity/User

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
@Component (value = "user")
public class User   {
    @Value(value = "1")
    private Integer id;
    @Value(value = "You")
    private String name;
@Resource //The default is role
    private Role role33;

    public Role getRole33() { return role33; }

    public Integer getId() { return id; }

    public String getName() { return name; }
}

8.4 entity/Role

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component//The default is role
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "Fresh student")
private String rName;

    public Integer getrId() {
        return rId;
    }

    public String getrName() {
        return rName;
    }
}

8.5 add applicationcontext.xml to the component scanner

<!--Declaration component scanner-->
<context:component-scan base-package="cn.kgc.entity"/>

8.6 test class TestSpring

  @Test
    public void testdemo01(){
      ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("name:"+user.getName()+"    rName:"+user.getRole33().getrName() );
} 

Result: name: you, rName: fresh student

9. Expansion:

@Similarities and differences between Component and @ Repository,@Service,@Controller

Same: you can create objects

Different: @ Component, @ Repository,@Service,@Controller have their own hierarchical roles
@Component entity class layer
@Repository dao layer
@service layer
@controller layer

Note: it's just a specification. In fact, anything can be used.

Digression:
The value in @ xxx(value = "") between implementation classes cannot be saved,
A single class can.

----2021.12.07

Keywords: Java Maven Spring

Added by TropicalBeach on Tue, 07 Dec 2021 09:23:30 +0200