We’ll focus on common annotations and gestures in Spring.

preface

The first two articles covered the basics of Sping IOC and the common way Spring uses annotations to assemble beans, These include @Component, @Repository, @Service, @Controller, @Autowired, @Resource, and @Qualifier. This article focuses on the remaining frequent annotations.

@ComponentScan

Previously we specified the scan path in applicationContext.xml so that Spring can scan the annotations below the package:

<! Use the context namespace to tell Spring to scan the specified directory for annotation parsing --> <context:component-scan base-package="com.java.annotation"/>
Copy the code

Then you need to import the configuration file when using:

ApplicationContext context =new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Pets pets=context.getBean("pets", Pets.class);
System.out.println(pets.toString());
Copy the code

Tell scanning path by means of XML configuration, it is too Low, we can use @ ComponentScan scanning path is specified, then through the Spring IoC container implementation class AnnotationConfigApplicationContext to produce container, use position is as follows:

@Data
@Service
@ComponentScan({"com.java.annotation.spring.bean.test5"})
public class Pets {
    @Resource
    private Dog dog;
    @Resource
    private Cat cat;
    public static void main(String args[]) {
        ApplicationContext context = newAnnotationConfigApplicationContext(Pets.class); Pets pets = context.getBean(Pets.class); System.out.println(pets.toString()); }}Copy the code

Spring will replace com. Java. The annotation. Spring. Beans. Test5 package below registered bean in the Spring, including Dog, Cat, and Pets, I need it before the sample has been in the configuration file to join Pets configuration, Isn’t it cool that we don’t even have the following line of code:

// just omit it
<bean id="pets" class="com.java.annotation.spring.bean.test5.Pets"/>
Copy the code

If @ComponentScan doesn’t specify a path, then by default only the current package is scanned, so entities and configuration packages must be consistent, but we don’t use this because we usually specify a path with this annotation. You can also specify which classes to scan, but these are not commonly used.

@ComponentScan(basePackageClasses = {Dog.class, Cat.class, Pets.class})
Copy the code

For an example of code that does not use @ComponentScan annotations, see the article “Spring Foundation series 1” assembling Beans based on annotations.

@Configuration

Instructs a class to declare one or more @Bean declared methods and is managed uniformly by the Spring container to generate Bean definitions and service requested classes for these beans at run time. Let’s start by defining a MyBean class:

public class MyBean {
    public MyBean(a){
        System.out.println("generate MyBean Instance");
    }
    public void init(a){
        System.out.println("MyBean Resources Initialized"); }}Copy the code

Define a MyConfiguration environment Configuration class via @Configuration:

@Configuration
@ToString
public class MyConfiguration {
    private String name = "Configuration test";
    @Bean
    public MyBean myBean(a){
        System.out.println("myBean Initialized");
        return newMyBean(); }}Copy the code

MyConfiguration is a configuration class that can be declared to manage multiple beans under this class. We declared a Bean of MyBean and expect it to be loaded and managed by the container.

Let’s look at the test case:

public static void main(String[] args) {
    ApplicationContext context1 = new AnnotationConfigApplicationContext(MyConfiguration.class);
    MyConfiguration myConfiguration = context1.getBean(MyConfiguration.class);
    System.out.println(myConfiguration.toString());
}
/ / output:
// myBean Initialized
// generate MyBean Instance
// MyConfiguration(name= config test)
Copy the code

As you can see from the output, the bean with the default name of myBean is loaded as the container is loaded. Since the myBean method returns a constructor of myBean, myBean is initialized, and MyConfiguration is then injected into the Spring framework as a bean.

In this way, we omit the configuration of MyBean in THE XML, and also omit the configuration of MyConfiguration and MyBean dependencies. I won’t post the XML configuration, which should be easy to write if you read my previous two articles.

@Bean

The @qualifier annotation defines the name of the factory method, the @scope annotation defines the Scope of the Bean, and the @qualifier annotation defines the Scope of the Bean. For example, singleton or Prototype.

The core of Spring’s new Java Configuration support is the @Configuration annotation class. These classes mainly include @Bean-annotated methods to define instances, configure, and initialize logic for Spring’s IoC container-managed objects. In addition to working with @Configuration, @bean itself has some unique uses, which I’ll extend briefly.

Accept life cycle callbacks

We can specify the life cycle of the Bean by making a simple change based on the code above:

@Configuration
@ToString
public class MyConfiguration {
    private String name = "Configuration test";
    @Bean(initMethod = "init") / / new init
    public MyBean myBean(a){
        System.out.println("myBean Initialized");
        return newMyBean(); }}Copy the code

Using the same test case, the output:

myBean Initialized
generate MyBean Instance
MyBean Resources Initialized // Add new outputMyConfiguration(name= configuration test)Copy the code

For the above example, the init() method can also be called manually, which is equivalent to the above method:

public MyBean myBean(a){
    System.out.println("myBean Initialized");
    MyBean myBean = new MyBean();
    myBean.init();
    return myBean;
}
Copy the code

The scope of the Bean

By default, all beans in the Spring application context are created as singletons. That is, no matter how many times a given bean is injected into other beans, the same instance is injected each time.

In most cases, singleton beans are an ideal solution. The cost of initializing and garbage collecting object instances is reserved for small-scale tasks where it may not make sense to keep objects stateless and reuse them repeatedly in your application.

Sometimes the classes used are mutable, they maintain some state, and therefore are not safe for reuse. In this case, the class should not be declared as a singleton bean because the object will be contaminated and unexpected problems will arise when reused.

@Configuration
@ToString
public class MyConfiguration {
    private String name = "Configuration test";
    @Bean(initMethod = "init")
    @Scope("prototype") // Add scope
    public MyBean myBean(a){
        System.out.println("myBean Initialized");
        return newMyBean(); }}Copy the code

Spring defines a variety of scopes:

  • Singleton: Only one instance of the bean is created throughout the application.
  • Prototype: A new bean instance is created each time it is injected or retrieved through the Spring application context.
  • Session: In a Web application, one bean instance is created for each Session.
  • Request (Rquest) : In a Web application, a bean instance is created for each request.

Beans defined through XML can specify their scope as follows:

<bean id="louzai" class="xxx" scope="prototype" />
Copy the code

Other uses of Bean

The Bean can be named:

@Bean(name="louzai")
public MyBean myBean(){
    System.out.println("myBean Initialized");
    return new MyBean();
}
Copy the code

Or specify an alias:

@Bean({"dataSource", "dataSourceA", "dataSourceB"})
public MyBean myBean(a){
    System.out.println("myBean Initialized");
    return new MyBean();
}
Copy the code

Or specify a description:

    @Bean(name="louzai")
    @description (" The bean name for this method is Louzai ")
    public MyBean myBean(a){
        System.out.println("myBean Initialized");
        return new MyBean();
    }
Copy the code

@bean is mainly used together with @Configuration to obtain Configuration data in the Configuration file. I will improve this part after I see this section. At present, only the basic usage is given.

@Transactional

Since there is a lot to be said for this note, which is very important on the one hand and very easy to pit on the other, I will leave it to the next article.

conclusion

For Java Spring, please refer to this article, “Spring Basics 2”, which is full of Spring IOC basics. For MVC, please refer to “Spring Basics 1”, which is full of beans based on annotations. Although not a member of the Spring family, I use Lombok annotations quite a lot. If you can refer to “Java Basics 1” Lombok annotations, and then add the annotations in this article, you will be able to master the most frequent annotations in Spring. If you come across other annotations later, I will continue this series.

The next article will focus on @Transactional and easy-to-encounter pits, and then I’ll start learning about AOP. I hope to finish my Spring basics this week.

Welcome everyone to like a lot, more articles, please pay attention to the wechat public number “Lou Zai advanced road”, point attention, do not get lost ~~