org.springframework.beans.factory.annotation.Qualifier Java Examples

The following examples show how to use org.springframework.beans.factory.annotation.Qualifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QualifierAnnotationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testQualifiedByParentValue() {
	StaticApplicationContext parent = new StaticApplicationContext();
	GenericBeanDefinition parentLarry = new GenericBeanDefinition();
	parentLarry.setBeanClass(Person.class);
	parentLarry.getPropertyValues().add("name", "ParentLarry");
	parentLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "parentLarry"));
	parent.registerBeanDefinition("someLarry", parentLarry);
	GenericBeanDefinition otherLarry = new GenericBeanDefinition();
	otherLarry.setBeanClass(Person.class);
	otherLarry.getPropertyValues().add("name", "OtherLarry");
	otherLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "otherLarry"));
	parent.registerBeanDefinition("someOtherLarry", otherLarry);
	parent.refresh();

	StaticApplicationContext context = new StaticApplicationContext(parent);
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	context.registerSingleton("testBean", QualifiedByParentValueTestBean.class);
	context.refresh();
	QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean");
	Person person = testBean.getLarry();
	assertEquals("ParentLarry", person.getName());
}
 
Example #2
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue("the real juergen");
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue("juergen imposter");
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	context.registerBeanDefinition("juergen1", person1);
	context.registerBeanDefinition("juergen2", person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #3
Source File: FramedbConfig.java    From erp-framework with MIT License 6 votes vote down vote up
@Bean(name = "framedbSqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("framedbDataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setPlugins(new Interceptor[]{ sqlInterceptor});

    bean.setDataSource(dataSource);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    Resource[] res = resolver.getResources("classpath:mapper/**");
    for (int i =0;i< res.length;i++) {
        if(res[i].getFilename().indexOf("xml")==-1){
            res[i] = null;
        }
    }
    bean.setMapperLocations(res);

    return bean.getObject();
}
 
Example #4
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldResolvesWithBaseQualifierAndDefaultValue() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class));
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldWithBaseQualifierDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	context.refresh();
	QualifiedFieldWithBaseQualifierDefaultValueTestBean bean =
			(QualifiedFieldWithBaseQualifierDefaultValueTestBean) context.getBean("autowired");
	assertEquals(MARK, bean.getPerson().getName());
}
 
Example #5
Source File: QualifierAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue("the real juergen");
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue("juergen imposter");
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	context.registerBeanDefinition("juergen1", person1);
	context.registerBeanDefinition("juergen2", person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #6
Source File: ControllerConfig.java    From rabbitmq-operator with Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("LABELS_TO_WATCH")
public Map<String, String> labelsToWatch() {
    final ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();

    if (System.getenv().containsKey(WATCH_LABELS_ENV_VAR)) {
        final String watchLabels = System.getenv().get(WATCH_LABELS_ENV_VAR);
        for (final String label : watchLabels.split(",")) {
            if (label.contains("=")) {
                final String[] keyValue = label.split("=");
                mapBuilder.put(keyValue[0], keyValue[1]);
            }
        }
    }

    return mapBuilder.build();
}
 
Example #7
Source File: MicroserviceSecurityConfiguration.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("loadBalancedRestTemplate")
   public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
       RestTemplate restTemplate = new RestTemplate();
       customizer.customize(restTemplate);
       return restTemplate;
   }
 
Example #8
Source File: ControllerConfig.java    From rabbitmq-operator with Apache License 2.0 5 votes vote down vote up
@Bean
public ServicesController servicesController(
        final KubernetesClient client,
        @Qualifier("LABELS_TO_WATCH") final Map<String, String> labelsToWatch
) {
    return new ServicesController(client, labelsToWatch);
}
 
Example #9
Source File: ConfigurationClassPostProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean(autowireCandidate = false)
Runnable testBean(Map<String, Runnable> testBeans,
		@Qualifier("systemProperties") Map<String, String> sysprops,
		@Qualifier("systemEnvironment") Map<String, String> sysenv) {
	this.testBeans = testBeans;
	assertSame(env.getSystemProperties(), sysprops);
	assertSame(env.getSystemEnvironment(), sysenv);
	return () -> {};
}
 
Example #10
Source File: EnodeEventStoreAutoConfig.java    From enode with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "spring.enode", name = "eventstore", havingValue = "mysql")
public MysqlEventStore mysqlEventStore(@Qualifier("enodeMysqlDataSource") DataSource mysqlDataSource, IEventSerializer eventSerializer) {
    MysqlEventStore eventStore = new MysqlEventStore(mysqlDataSource, DBConfiguration.mysql(), eventSerializer);
    vertx.deployVerticle(eventStore, res -> {
    });
    return eventStore;
}
 
Example #11
Source File: RqueueUtilityServiceImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Autowired
public RqueueUtilityServiceImpl(
    RqueueConfig rqueueConfig,
    RqueueWebConfig rqueueWebConfig,
    @Qualifier("stringRqueueRedisTemplate") RqueueRedisTemplate<String> stringRqueueRedisTemplate,
    RqueueSystemConfigDao rqueueSystemConfigDao,
    RqueueMessageTemplate rqueueMessageTemplate,
    RqueueMessageMetadataService messageMetadataService) {
  this.stringRqueueRedisTemplate = stringRqueueRedisTemplate;
  this.rqueueSystemConfigDao = rqueueSystemConfigDao;
  this.rqueueWebConfig = rqueueWebConfig;
  this.rqueueConfig = rqueueConfig;
  this.rqueueMessageTemplate = rqueueMessageTemplate;
  this.messageMetadataService = messageMetadataService;
}
 
Example #12
Source File: UaaSignatureVerifierClient.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
                              OAuth2Properties oAuth2Properties) {
    this.restTemplate = restTemplate;
    this.oAuth2Properties = oAuth2Properties;
    // Load available UAA servers
    discoveryClient.getServices();
}
 
Example #13
Source File: RecipientStatController.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public RecipientStatController(BirtStatisticsService birtStatisticsService, ComTargetService targetService,
                               @Qualifier("MediaTypesService") MediaTypesService mediaTypesService, ConversionService conversionService,
                               MailinglistApprovalService mailinglistApprovalService, UserActivityLogService userActivityLogService) {
    this.birtStatisticsService = birtStatisticsService;
    this.targetService = targetService;
    this.mediaTypesService = mediaTypesService;
    this.conversionService = conversionService;
    this.mailinglistApprovalService = mailinglistApprovalService;
    this.userActivityLogService = userActivityLogService;
}
 
Example #14
Source File: FactoryMethodComponent.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean @BeanAge(1)
protected TestBean protectedInstance(@Qualifier("public") TestBean spouse, @Value("#{privateInstance.age}") String country) {
	TestBean tb = new TestBean("protectedInstance", 1);
	tb.setSpouse(tb);
	tb.setCountry(country);
	return tb;
}
 
Example #15
Source File: ControllerConfig.java    From rabbitmq-operator with Apache License 2.0 5 votes vote down vote up
@Bean
public SecretsController secretsController(
        final KubernetesClient client,
        @Qualifier("LABELS_TO_WATCH") final Map<String, String> labelsToWatch
) {
    return new SecretsController(client, labelsToWatch, (val) -> new String(Base64.getDecoder().decode(val), StandardCharsets.UTF_8));
}
 
Example #16
Source File: ControllerConfig.java    From rabbitmq-operator with Apache License 2.0 5 votes vote down vote up
@Bean
public NetworkPartitionResourceController networkPartitionResourceController(
        final KubernetesClient client,
        @Qualifier("LABELS_TO_WATCH") final Map<String, String> labelsToWatch
) {
    return new NetworkPartitionResourceController(client, labelsToWatch);
}
 
Example #17
Source File: PrimaryConfig.java    From txle with Apache License 2.0 5 votes vote down vote up
@Primary
@Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource, EntityManagerFactoryBuilder builder) {
    return builder.dataSource(primaryDataSource)
            .properties(jpaProperties.getProperties())
            .packages("com.actionsky.txle.grpc.entity")
            .persistenceUnit("primaryPersistenceUnit")
            .build();
}
 
Example #18
Source File: SpringSwagger3Configuration.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
@Bean
SpringSwagger3Controller _springSwagger3Controller(@Qualifier("swagger3") IRestDocParser docParser) {
    SwaggerUIConfiguration uiConfiguration;
    try {
        uiConfiguration = _applicationContext.getBean(SwaggerUIConfiguration.class);
    } catch (NoSuchBeanDefinitionException e) {
        uiConfiguration = new SwaggerUIConfiguration();
    }
    var controller = new SpringSwagger3Controller(docParser, uiConfiguration);
    return controller;
}
 
Example #19
Source File: UaaSignatureVerifierClient.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
                              OAuth2Properties oAuth2Properties) {
    this.restTemplate = restTemplate;
    this.oAuth2Properties = oAuth2Properties;
    // Load available UAA servers
    discoveryClient.getServices();
}
 
Example #20
Source File: ShardingDataSourceConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
	SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
	bean.setDataSource(dataSource);
	bean.setMapperLocations(
			new PathMatchingResourcePatternResolver().getResources("classpath*:com/central/**/dao/*.xml"));
	return bean.getObject();
}
 
Example #21
Source File: JdbcConnectionRepositoryConfig.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean("jdbcDirectoryBasedFileConfigurationLoader")
public DirectoryBasedFileConfigurationLoader<NamedConnectionConfiguration> jdbcDirectoryBasedFileConfigurationLoader(
        @Autowired PropertiesNamedConnectionConfigurationParser propertiesConfigurationParser,
        @Autowired @Qualifier("filenameSupplier") Supplier<String, String> filenameSupplier,
        @Autowired @Qualifier("configurationIdSupplier") Supplier<String, String> configurationIdSupplier) {
    DirectoryBasedFileConfigurationLoader<NamedConnectionConfiguration> loader = new DirectoryBasedFileConfigurationLoader<NamedConnectionConfiguration>();
    loader.setFilenameSupplier(filenameSupplier);
    loader.setConfigurationIdSupplier(configurationIdSupplier);
    loader.setConfigurationParser(propertiesConfigurationParser);
    return loader;
}
 
Example #22
Source File: UaaSignatureVerifierClient.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
                              OAuth2Properties oAuth2Properties) {
    this.restTemplate = restTemplate;
    this.oAuth2Properties = oAuth2Properties;
    // Load available UAA servers
    discoveryClient.getServices();
}
 
Example #23
Source File: JeesuiteConfig.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
@Bean
public JedisProviderFactoryBean initJedisProvider(@Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig){
    JedisProviderFactoryBean jedisProviderFactoryBean = new JedisProviderFactoryBean();
    jedisProviderFactoryBean.setJedisPoolConfig(jedisPoolConfig);
    jedisProviderFactoryBean.setServers(Global.getConfig("feiqu-redis.servers"));
    jedisProviderFactoryBean.setPassword(AESUtil.aesDecode(Global.getConfig("feiqu-redis.password")));
    jedisProviderFactoryBean.setMode(Global.getConfig("feiqu-redis.mode"));

    return jedisProviderFactoryBean;
}
 
Example #24
Source File: DataSourceConfig.java    From springboot-link-admin with Apache License 2.0 5 votes vote down vote up
@Bean(name = "baseDataSource")
@Qualifier("baseDataSource")
@ConfigurationProperties(prefix = "spring.datasource.base")
@Primary
public DataSource primaryDataSource() {
	return DataSourceBuilder.create().build();
}
 
Example #25
Source File: ApplicationContextExpressionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Autowired
public ConstructorValueTestBean(
		@Value("XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ") String name,
		@Value("#{mySpecialAttr}") int age,
		@Qualifier("original") TestBean tb,
		@Value("${code} #{systemProperties.country}") String country) {
	this.name = name;
	this.age = age;
	this.country = country;
	this.tb = tb;
}
 
Example #26
Source File: EmailMessageTemplateAutoConfiguration.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean(MessageConstants.EMAIL_TEMPLATE_ENGINE_BEAN)
public TemplateEngine templateEngine(@Qualifier(MessageConstants.EMAIL_TEMPLATE_RESOLVER_BEAN) SpringResourceTemplateResolver templateResolver) {
	SpringTemplateEngine engine = new SpringTemplateEngine();
	engine.addDialect(new Java8TimeDialect());
	engine.addTemplateResolver(templateResolver);
	engine.getConfiguration();

	return engine;
}
 
Example #27
Source File: DataSourceConfig.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Bean
public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
                                      @Qualifier("slave1DataSource") DataSource slave1DataSource,
                                      @Qualifier("slave2DataSource") DataSource slave2DataSource) {
    Map<Object, Object> targetDataSources = new HashMap<>();
    targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);
    targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource);
    targetDataSources.put(DBTypeEnum.SLAVE2, slave2DataSource);
    RoutingDataSource routingDataSource = new RoutingDataSource();
    routingDataSource.setDefaultTargetDataSource(masterDataSource);
    routingDataSource.setTargetDataSources(targetDataSources);
    return routingDataSource;
}
 
Example #28
Source File: MasterDataSourcesConfig.java    From springboot-learn with MIT License 5 votes vote down vote up
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
    final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));
    return sessionFactoryBean.getObject();
}
 
Example #29
Source File: UaaSignatureVerifierClient.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
                              OAuth2Properties oAuth2Properties) {
    this.restTemplate = restTemplate;
    this.oAuth2Properties = oAuth2Properties;
    // Load available UAA servers
    discoveryClient.getServices();
}
 
Example #30
Source File: MybatisConfig.java    From light-reading-cloud with MIT License 5 votes vote down vote up
/** 工厂配置 */
@Bean
public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("accountCenterDataSource") DataSource dataSource) throws Exception {
    // 设置数据源
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);

    // 添加XML映射
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    factory.setMapperLocations(resolver.getResources(MAPPER_LOCATIONS));

    //添加插件
    factory.setPlugins(new Interceptor[]{ this.getPageHelper() });
    return factory.getObject();
}