栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringAnnotaiton(一)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringAnnotaiton(一)

文章目录
    • SpringAnnotaiton(一)
      • Conditional注解
      • Primary、Qualifier注解
        • Primary
      • import、importResource
        • 持续跟新

SpringAnnotaiton(一)
  • Conditional
Conditional注解

PorscheCar类

public class PorscheCar implements Car{
    @Override
    public String toString() {
        return "PorscheCar{}";
    }
}

CarFactory类实现Condition接口

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypemetadata;
public class CarFactory implements Condition{
    public boolean matches(ConditionContext context, AnnotatedTypemetadata metadata) {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        try {
            Object carFactory = beanFactory.getBean("carFactory");
        }catch (Exception ex){
            return false;
        }
        return true;
    }
}

JavaConfig配置Bean

@Configuration
public class SpringJavaConfig02 {
    
    @Bean
    @Conditional(CarFactory.class)
    public Car porscheCar(){
        return new PorscheCar();
    }
}

测试类

@Test
public void test06(){
    AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(SpringJavaConfig02.class);
    System.out.println(acac.getBean("porscheCar", PorscheCar.class));
}

配置文件中放开CarFactoryBean的创建后

Primary、Qualifier注解 Primary

Car接口

public interface Car {
}

Car实现类 PorscheCar、BMWCar

@Component
public class PorscheCar implements Car{

    @Override
    public String toString() {
        return "PorscheCar{}";
    }
}
@Component
public class BMWCar implements Car{
    @Override
    public String toString() {
        return "BMWCar{}";
    }
}

FourSStores类

@Component
public class FourSStores {
    @Autowired
    private Car car;

    @Override
    public String toString() {
        return "FourSStores{" +
                "car=" + car +
                '}';
    }
}

扫描注解配置类

@Configuration
@ComponentScan(value = "com.test.springdome02")
public class SpringConfig {
}

测试类

@Test
    public void test07(){
        AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(SpringConfig.class);
        System.out.println(acac.getBean("fourSStores", FourSStores.class));
    }

给BMWCar增加Primary注解

@Component
@Primary
public class BMWCar implements Car{}

import、importResource 持续跟新
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号