Introduction to Spring learning record: introduction annotation development

Posted by sdjensen on Thu, 02 Dec 2021 22:09:05 +0100

In fact, learning Spring, on the one hand, is to simplify the development cycle, on the other hand, it can use Spring annotations and XML configuration and hand it over to Spring to help manage, saving a lot of unnecessary tedious things. However, because Spring's XML is too annoying, it is now commonly used to replace XML with annotations for annotation development. (mainly because XML can't remember sometimes, it's easy to forget, and you want to be lazy ~)

1, Spring management annotations commonly used for getting started.

1.@Component classes other than layer 3

2.@Controller hands over the classes of the web layer to spring for management. Because the Servlet/Filter object cannot be managed by spring, we choose to replace the Servlet and adopt the new framework spring MVC! (after all, that thing prevents us from being lazy, so we have to find a way to kill it)

3.@Service gives the business classes of the business layer to spring management

4.@Repository gives the Dao class of Dao layer to spring management

So how to use it?

2, Take a simple example.

① Now add Spring dependencies to pom.xml:

   <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

② Write a DAO layer interface called UserDAO and its implementation class UserDAOImpl:

//It's separate here, but I'm lazy to put it together

//UserDAO interface
public interface UserDAO {
    public void testDAO();
}

//UserDAOImpl implementation class
import com.test.dao.UserDAO;
import org.springframework.stereotype.Repository;

//Leave the userDAOImpl to Spring and name it userDAO
@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

    public void testDAO() {
        System.out.println("This is DAO layer");
    }
}

③ Write a UserService interface and UserServiceImpl implementation class

//It's also separate here. Don't ask. I'm lazy
//Interface
public interface UserService {
    public void UserService();
}

//Implementation class
//@The service is managed by Spring
@Service
public class UserServiceImpl implements UserService {

//  Automatically inject the userDAO just handed over to Spring management according to the type
    @Autowired
    private UserDAO userDAO;

    public void UserService() {
        System.out.println("This is service");
    }
}

  ④ Then we start Spring annotation scanning in the Spring configuration file applicationContext.xml:

This configuration is used to enable Spring to scan the entity classes that we have added annotations to the project, and then we inject this entity class object into other entity classes through annotations.

Base package refers to the package we need to scan and its descendants

<!-- base-package We put the code under the package. Here, as long as the file you want to scan is within this range, you can name it casually -->
<context:component-scan base-package="com.test"/>

⑤ Then we go to Test and write a Test class:

public class UserServiceTest {

    public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    public static UserService userService1 = (UserService) context.getBean("userService");

    @Test
    public void test(){
        userService1.UserService();
    }
}

Then look at the results:

We can see that the userDAO object in our Service class has successfully injected and run the testDAO() method.

So can we be a little more concise? Steal some more laziness? The answer is: Yes!

Therefore, we use annotations to load xml:

1.@RunWith(SpringJUnit4ClassRunner.class)    // To create a Spring container and inject test classes, you need bean s
2.@ContextConfiguration("classpath:applicationContext.xml")    // Specifies the configuration file for the loaded spring

Then we pass@

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceTest {


    public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    public static UserService userService1 = (UserService) context.getBean("userService");

    @Autowired
    private UserService userService2;
    
    @Test
    public void test(){
        userService1.UserService();
        System.out.println("=========");
        userService2.UserService();
    }

Then look at the results:

  Perfect replacement!

So we can write it in pure annotation form:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceTest {

    @Autowired
    private UserService userService2;
    
    @Test
    public void test(){
        userService2.UserService();
    }
}

So this is the benefit of annotation development! Can be more convenient and concise!

Of course, if you don't trust this automatic injection and are afraid of making mistakes, we can also manually specify type injection:

Add a @ Qualifier() tag and fill in the type name you want!

By default, the name here should be consistent with the class name of the type you selected, but if you specify a name for the class you specify, you need to change it to the specified name:

 

3, The difference between the newly created entity class object and the entity class object managed by Spring.

So, now throw a question: if we manually create an entity class object, can @ Autowired in this entity class object still take effect? Will Spring automatically help us inject?

No nonsense, directly test the code:

Then the result is:

  That is: the userDAO in our class is empty!

So the result is: the newly created userService3 entity class object Spring will not help us inject it automatically!

  reason:

        Because Spring will only automatically inject the entity class objects they want for the entity class objects that have been handed over to Spring management! The newly created entity class object is not the object managed by the Spring container, but a completely different object. This object is not managed by the Spring container, so Spring will not scan it (even if we add the @ Service annotation).

        In fact, no matter how many different other entity class objects are injected into the userService entity class object after you hand it over to Spring object management, the userService object in these entity class objects is the same!

Topics: Java Spring Back-end