1 Import导入bean的四种方式

2 代码

2.1 要导入的bean

package com.example.demo;

public class MyUser {
}
package com.example.demo;

public class MyRow {
}

2.2 各种方式的代码

2.2.1 @Import(MyUser.class)

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.demo.MyUser;
import com.example.demo.UserConfig;
import org.springframework.context.annotation.Import;

import java.util.Map;

@SpringBootApplication
@Import(MyUser.class)
//@Import(UserConfig.class)
//@Import(MyImportSelecter.class)
//@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo2Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Demo2Application.class, args);
        //User user = (User) configurableApplicationContext.getBean("user");
        //System.out.println(user);
        //MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser2");
        MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser");
        System.out.println(myUser);

        //Map<String,MyUser> map = configurableApplicationContext.getBeansOfType(MyUser.class);
        //System.out.println(map);
    }

}

2.2.2 @Import(UserConfig.class)

package com.example.demo;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {
    @Bean
    public MyUser myUser(){
        return  new MyUser();
    }

    @Bean
    public MyRow myRow(){
        return  new MyRow();
    }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.demo.MyUser;
import com.example.demo.UserConfig;
import org.springframework.context.annotation.Import;

import java.util.Map;

@SpringBootApplication
//@Import(MyUser.class)
@Import(UserConfig.class)
//@Import(MyImportSelecter.class)
//@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo2Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Demo2Application.class, args);
        //User user = (User) configurableApplicationContext.getBean("user");
        //System.out.println(user);
        //MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser2");
        MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser");
        System.out.println(myUser);

        //Map<String,MyUser> map = configurableApplicationContext.getBeansOfType(MyUser.class);
        //System.out.println(map);
    }

}

2.2.3 @Import(MyImportSelecter.class)

package com.example.demo;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportSelecter implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.example.demo.MyUser","com.example.demo.MyRow"};
    }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.demo.MyUser;
import com.example.demo.UserConfig;
import org.springframework.context.annotation.Import;

import java.util.Map;

@SpringBootApplication
//@Import(MyUser.class)
//@Import(UserConfig.class)
@Import(MyImportSelecter.class)
//@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo2Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Demo2Application.class, args);
        //User user = (User) configurableApplicationContext.getBean("user");
        //System.out.println(user);
        //MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser2");
        MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser");
        System.out.println(myUser);

        //Map<String,MyUser> map = configurableApplicationContext.getBeansOfType(MyUser.class);
        //System.out.println(map);
    }

}

2.2.4 @Import(MyImportBeanDefinitionRegistrar.class)

package com.example.demo;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(MyUser.class).getBeanDefinition();
        registry.registerBeanDefinition("myUser2",beanDefinition);
    }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.demo.MyUser;
import com.example.demo.UserConfig;
import org.springframework.context.annotation.Import;

import java.util.Map;

@SpringBootApplication
//@Import(MyUser.class)
//@Import(UserConfig.class)
//@Import(MyImportSelecter.class)
@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo2Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Demo2Application.class, args);
        //User user = (User) configurableApplicationContext.getBean("user");
        //System.out.println(user);
        MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser2");
        //MyUser myUser = (MyUser) configurableApplicationContext.getBean("myUser");
        System.out.println(myUser);

        Map<String,MyUser> map = configurableApplicationContext.getBeansOfType(MyUser.class);
        System.out.println(map);
    }

}

3 运行结果 仅以2.2.4的运行结果为例,其他结果都大概相同。

C:\Users\ThinkPad\.jdks\openjdk-21.0.2\bin\java.exe -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-Dmanagement.endpoints.jmx.exposure.include=*" "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2023.3.2\lib\idea_rt.jar=54699:D:\Program Files\JetBrains\IntelliJ IDEA 2023.3.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\ThinkPad\IdeaProjects\untitled7\demo2\target\classes;C:\Users\ThinkPad\.m2\repository\org\springframework\boot\spring-boot-starter-data-redis\3.2.2\spring-boot-starter-data-redis-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\boot\spring-boot-starter\3.2.2\spring-boot-starter-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\boot\spring-boot\3.2.2\spring-boot-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-context\6.1.3\spring-context-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-expression\6.1.3\spring-expression-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\io\micrometer\micrometer-observation\1.12.2\micrometer-observation-1.12.2.jar;C:\Users\ThinkPad\.m2\repository\io\micrometer\micrometer-commons\1.12.2\micrometer-commons-1.12.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\3.2.2\spring-boot-autoconfigure-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\boot\spring-boot-starter-logging\3.2.2\spring-boot-starter-logging-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\ch\qos\logback\logback-classic\1.4.14\logback-classic-1.4.14.jar;C:\Users\ThinkPad\.m2\repository\ch\qos\logback\logback-core\1.4.14\logback-core-1.4.14.jar;C:\Users\ThinkPad\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.21.1\log4j-to-slf4j-2.21.1.jar;C:\Users\ThinkPad\.m2\repository\org\apache\logging\log4j\log4j-api\2.21.1\log4j-api-2.21.1.jar;C:\Users\ThinkPad\.m2\repository\org\slf4j\jul-to-slf4j\2.0.11\jul-to-slf4j-2.0.11.jar;C:\Users\ThinkPad\.m2\repository\jakarta\annotation\jakarta.annotation-api\2.1.1\jakarta.annotation-api-2.1.1.jar;C:\Users\ThinkPad\.m2\repository\org\yaml\snakeyaml\2.2\snakeyaml-2.2.jar;C:\Users\ThinkPad\.m2\repository\io\lettuce\lettuce-core\6.3.1.RELEASE\lettuce-core-6.3.1.RELEASE.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-common\4.1.105.Final\netty-common-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-handler\4.1.105.Final\netty-handler-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-resolver\4.1.105.Final\netty-resolver-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-buffer\4.1.105.Final\netty-buffer-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-transport-native-unix-common\4.1.105.Final\netty-transport-native-unix-common-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-codec\4.1.105.Final\netty-codec-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\netty\netty-transport\4.1.105.Final\netty-transport-4.1.105.Final.jar;C:\Users\ThinkPad\.m2\repository\io\projectreactor\reactor-core\3.6.2\reactor-core-3.6.2.jar;C:\Users\ThinkPad\.m2\repository\org\reactivestreams\reactive-streams\1.0.4\reactive-streams-1.0.4.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\data\spring-data-redis\3.2.2\spring-data-redis-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\data\spring-data-keyvalue\3.2.2\spring-data-keyvalue-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\data\spring-data-commons\3.2.2\spring-data-commons-3.2.2.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-tx\6.1.3\spring-tx-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-beans\6.1.3\spring-beans-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-oxm\6.1.3\spring-oxm-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-aop\6.1.3\spring-aop-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-context-support\6.1.3\spring-context-support-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\redis\clients\jedis\5.2.0-alpha2\jedis-5.2.0-alpha2.jar;C:\Users\ThinkPad\.m2\repository\org\slf4j\slf4j-api\2.0.11\slf4j-api-2.0.11.jar;C:\Users\ThinkPad\.m2\repository\org\apache\commons\commons-pool2\2.12.0\commons-pool2-2.12.0.jar;C:\Users\ThinkPad\.m2\repository\org\json\json\20231013\json-20231013.jar;C:\Users\ThinkPad\.m2\repository\com\google\code\gson\gson\2.10.1\gson-2.10.1.jar;C:\Users\ThinkPad\IdeaProjects\untitled7\demo1\target\classes;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-core\6.1.3\spring-core-6.1.3.jar;C:\Users\ThinkPad\.m2\repository\org\springframework\spring-jcl\6.1.3\spring-jcl-6.1.3.jar com.example.demo.Demo2Application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.2)

2024-01-30T22:17:31.449+08:00  INFO 6600 --- [           main] com.example.demo.Demo2Application        : Starting Demo2Application using Java 21.0.2 with PID 6600 (C:\Users\ThinkPad\IdeaProjects\untitled7\demo2\target\classes started by ThinkPad in C:\Users\ThinkPad\IdeaProjects\untitled7)
2024-01-30T22:17:31.452+08:00  INFO 6600 --- [           main] com.example.demo.Demo2Application        : No active profile set, falling back to 1 default profile: "default"
2024-01-30T22:17:31.906+08:00  INFO 6600 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode
2024-01-30T22:17:31.909+08:00  INFO 6600 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2024-01-30T22:17:31.932+08:00  INFO 6600 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10 ms. Found 0 Redis repository interfaces.
2024-01-30T22:17:32.585+08:00  INFO 6600 --- [           main] com.example.demo.Demo2Application        : Started Demo2Application in 1.575 seconds (process running for 2.359)
com.example.demo.MyUser@27df95e
{myUser=com.example.demo.MyUser@b46e103, myUser2=com.example.demo.MyUser@27df95e}

Process finished with exit code 0
01-31 08:02