//@Bean //不指定value时,默认将方法名称当成ID,当指定value时,name就是其value;类型(class)就是返回值的类型,老版本的是name
举例:
@Bean("myUser")
public User user() {
return new User("李四", "1234565");
}
/*
* @Scope 作用域:
* singleton(单实例):默认的选项,IOC容器一启动就创建对象放在IOC容器中,以后每次都是在这个容器里面拿,只会创建一次
* prototype(多实例):IOC容器启动时不会创建对象,每次获取的时候才会去调用方法创建对象放在IOC容器中,每次创建都是一个不同的对象值
*/
/*
* @Lazy
懒加载
* 单实例bean在容器启动时就创建对象,而懒加载可以使其启动时不加载,在使用(获取)这个bean时再创建对象(注意:单实例只会创建一次对象)
*/
/*
* @Conditional({Condition}):按照一定的条件进行判断,满足条件才给容器中注册这个bean
* (spring4.0以后的版本才有)
* Condition:条件:
* 自定义条件:WindowsCondition.java,LinuxCondition.java
* 因为它的目标为@Target({ElementType.TYPE,
ElementType.METHOD}),所有不仅能用在方法上,还能用在类上(类中组件统一设置):
* 当用在类上时,表示满足该条件才会去注册这个类下面的bean
*/
举例:
@Conditional({WindowsCondition.class})
@Bean("bill")
public User user01() {
return new User("bill", "@Conditional");
}
@Conditional({LinuxCondition.class})
@Bean("linus")
public User user02() {
return new User("linus", "@Conditional");
}
WindowsCondition.class:
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 1:获取当前IOC容器使用的bean工厂:
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 2:获取当前IOC容器的类加载器
ClassLoader classLoader = context.getClassLoader();
// 3:获取当前运行环境
Environment environment = context.getEnvironment();
// 4:获取bean定义的注册类(比如user.class)
BeanDefinitionRegistry registry = context.getRegistry();
// 4:获取资源加载器
ResourceLoader resourceLoader = context.getResourceLoader();
// 通过运行环境获取到当前的操作系统是不是Linux
String property = environment.getProperty("os.name");
if (property.contains("Windows")) {
return true;
}
return false;
}
}
LinuxCondition.class:
public class LinuxCondition
implements
Condition {
//ConditionContext:判断条件能使用的上下文环境
//AnnotatedTypeMetadata:注释信息
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//1:获取当前IOC容器使用的bean工厂:
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//2:获取当前IOC容器的类加载器
ClassLoader classLoader = context.getClassLoader();
//3:获取当前运行环境
Environment environment = context.getEnvironment();
//4:获取bean定义的注册类(比如user.class)
BeanDefinitionRegistry registry = context.getRegistry();
//4:获取资源加载器
ResourceLoader resourceLoader = context.getResourceLoader();
//通过运行环境获取到当前的操作系统是不是Linux
String property = environment.getProperty("os.name");
if(property.contains("linux")) {
return true;
}
return false;
}
}