Several ways spring gets bean s

Keywords: Programming Spring Java Maven Apache

Use jdk:1.8, maven:3.3.3

How spring gets beans

Contents of the pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.ac.iie</groupId>
    <artifactId>spring-course</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>
    </dependencies>
</project>

Configuration class MyConfig.java:

package com.edu.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration Class
 */

@Configuration
public class MyConfig {

    // Configure a bean
    @Bean
    public MyBean createMyBean(){
        return new MyBean();
    }

}

MyBean.java

package com.edu.spring;

public class MyBean {
}

Main function: App.java

package com.edu.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        // Get Beans from Containers - Get from Types
        System.out.println(context.getBean(MyBean.class));
        // Get Beans from Container - Get Beans from Name, default name is method name
        System.out.println(context.getBean("createMyBean"));
        context.close();
    }
}

The output is as follows:

com.edu.spring.MyBean@1445d7f
com.edu.spring.MyBean@1445d7f

If you need to specify a bean name, you need to modify MyConfig.java:

@Configuration
public class MyConfig {

    // Configure a bean
    @Bean(name = "myBean")
    public MyBean createMyBean(){
        return new MyBean();
    }

}

Then specify the name of the Bean in App.java: you won't be able to get the Bean from the method name.

public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        // Get Beans from Containers - Get from Types
        System.out.println(context.getBean(MyBean.class));
        // Get Beans from Container - Get Beans from Name, default name is method name
        // System.out.println(context.getBean("createMyBean"));
        // Get the bean from the container--Get it from the specified name
        System.out.println(context.getBean("myBean"));
        context.close();
    }
}

Bean defaults to singleton

As we can see, Bean is singular, and the objects printed twice are the same.

If we want to modify Bean's singletons as multiple cases, modify MyConfig.java as follows (add scope(prototype):

@Configuration
public class MyConfig {

    // Configure a bean
    @Bean(name = "myBean")
    @Scope("prototype")
    public MyBean createMyBean(){
        return new MyBean();
    }

}

Print as follows:

com.edu.spring.MyBean@10b48321
com.edu.spring.MyBean@6b67034

FactoryBean

New Method JeepFactoryBean.java

package com.edu.spring;

import org.springframework.beans.factory.FactoryBean;

public class JeepFactoryBean implements FactoryBean<Jeep> {

    /**
     * Instance object created
     * @return
     * @throws Exception
     */
    @Override
    public Jeep getObject() throws Exception {
        return new Jeep();
    }

    /**
     *
     * @return
     */
    @Override
    public Class<?> getObjectType() {
        return Jeep.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

Add configuration in MyConfig.java:

    @Bean
    public JeepFactoryBean createJeepFactoryBean(){
        return new JeepFactoryBean();
    }

You can get Jeep.class in App.java.

System.out.println(context.getBean(Jeep.class));
System.out.println(context.getBean("createJeepFactoryBean"));

If you want to get the JeepFactoryBean itself, not the classes produced by the factory, you can do so in two ways:

System.out.println(context.getBean(JeepFactoryBean.class));
System.out.println(context.getBean("&createJeepFactoryBean"));

There are two ways to assemble beans, one using Factory Bean and the other using the original method

Use the third type of assembly

New CarFactory.java

public class CarFactory {
    public Car create(){
        return new Car();
    }
}

New Car.java

Configure MyConfig.java

    @Bean
    public Car createJeep(CarFactory carFactory){
        return carFactory.create();
    }

    @Bean
    public CarFactory createCarFactory(){
        return new CarFactory();
    }

Get the object:

System.out.println(context.getBean(Car.class));

Because, during Bean assembly, when parameters are required, spring gets the corresponding parameters from the current container by default and injects them.

Bean initialization, when the Bean is initialized, does some work.

Mode 1:

Create Cat.java

package com.edu.spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Cat implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("====afterPropertiesSet====");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("====destroy====");
    }
}

Configure MyConfig.java


    @Bean
    public Cat createCat(){
        return new Cat();
    }

Get cat

System.out.println(context.getBean(Cat.class));

Console Printing:

====afterPropertiesSet====
com.edu.spring.MyBean@7fe8ea47
com.edu.spring.MyBean@226a82c4
com.edu.spring.JeepFactoryBean@731f8236
com.edu.spring.JeepFactoryBean@731f8236
com.edu.spring.Jeep@255b53dc
com.edu.spring.Jeep@255b53dc
com.edu.spring.Car@1dd92fe2
com.edu.spring.Cat@6b53e23f
====destroy====

Method 2:

Create Dog.java

package com.edu.spring;

public class Dog {
    public void myInit(){
        System.out.println("init=====");
    }
    public void myDestory(){
        System.out.println("destory===");
    }

}

Specify the method to execute at initialization and destroy when configuring MyConfig.java

    @Bean(initMethod = "myInit", destroyMethod = "myDestory")
    public Dog createDog(){
        return new Dog();
    }

Mode 3:

New Fish.java

package com.edu.spring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Fish {

    @PostConstruct
    public void initial(){
        System.out.println("fish init");
    }

    @PreDestroy
    public void close(){
        System.out.println("fish close");
    }

}

Configure MyConfig.java

    @Bean
    public Fish createFish(){
        return new Fish();
    }

Bean assembly

New User.java

package com.edu.spring;

import org.springframework.stereotype.Component;

@Component
public class User {
}

Modify App.java to make User.class

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class, User.class);
System.out.println(context.getBean(User.class));

But use @Component Cannot set the initialization and destruction methods using @Bean(initMethod = "myInit", destroyMethod = "myDestory")

In addition, the default name is the class name.You can specify a name:

@Component("myUser")

Posted by salim on Tue, 07 May 2019 13:05:38 -0700