org.example.config.MyConfig类
package org.example.config;
import org.springframework.context.annotation.Configuration;
/**
* @author Administrator
*/
@Configuration
public class MyConfig {
}
org.example.pojo.People类
package org.example.pojo;
/**
* @author Administrator
*/
public class People {
}
org.example.config.MyConfig2类
package org.example.config;
import org.example.pojo.People;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
/**
* @author Administrator
*/
@Configuration
@ConditionalOnBean(People.class)
public class MyConfig2 {
}
org.example.App类
package org.example;
import org.example.config.MyConfig2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author Administrator
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
System.out.println(context.getBean(MyConfig2.class));
}
}
运行App,控制台打印
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.example.config.MyConfig2' available
因为@ConditionalOnBean(People.class)的意思是要IOC容器里面有People.class类型的bean才在容器里构建MyConfig2类型的bean,在MyConfig类上引入People.class类型的bean
@Import(People.class)
再运行App,控制台打印
org.example.config.MyConfig2$$EnhancerBySpringCGLIB$$a57c6de6@894858
在App中添加代码
package org.example;
import org.example.config.MyConfig2;
import org.example.pojo.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author Administrator
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
System.out.println(context.getBean(MyConfig2.class));
System.out.println(context.getBean(People.class));
}
}
再运行,控制台打印
org.example.config.MyConfig2$$EnhancerBySpringCGLIB$$f00a1196@18151a14
org.example.pojo.People@64711bf2
还有其他的按条件构建bean
@ConditionalOnBean注解可以添加的类上,也可以添加到方法上