下面列出了org.springframework.context.ApplicationContextAware#org.springframework.beans.factory.config.AutowireCapableBeanFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@BeforeEach
void beforeMethod() throws IOException, OWLOntologyCreationException, NoSuchMethodException {
// ontology repository collection is not spring managed, see FileRepositoryCollectionFactory
File file = ResourceUtils.getFile("small_test_data_NGtest.owl.zip");
OntologyRepositoryCollection ontologyRepoCollection =
BeanUtils.instantiateClass(
OntologyRepositoryCollection.class.getConstructor(File.class), file);
autowireCapableBeanFactory.autowireBeanProperties(
ontologyRepoCollection, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
ontologyRepoCollection.init();
ontologyRepository = ontologyRepoCollection.getRepository(ONTOLOGY);
ontologyTermDynamicAnnotationRepository =
ontologyRepoCollection.getRepository(ONTOLOGY_TERM_DYNAMIC_ANNOTATION);
ontologyTermNodePathRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_NODE_PATH);
ontologyTermSynonymRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_SYNONYM);
ontologyTermRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM);
}
protected void autowireContext(Component instance) {
AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
autowireBeanFactory.autowireBean(instance);
if (instance instanceof ApplicationContextAware) {
((ApplicationContextAware) instance).setApplicationContext(applicationContext);
}
if (instance instanceof InitializingBean) {
try {
((InitializingBean) instance).afterPropertiesSet();
} catch (Exception e) {
throw new RuntimeException(
"Unable to initialize UI Component - calling afterPropertiesSet for " +
instance.getClass(), e);
}
}
}
@Test
public void testAutowireBeanByTypeWithTwoPrimaryCandidates() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPrimary(true);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
bd2.setPrimary(true);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertNotNull("Exception should have cause", ex.getCause());
assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass());
}
}
@Test
public void testAutowireWithSatisfiedJavaBeanDependency() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "Rod");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("rod", bd);
assertEquals(1, lbf.getBeanDefinitionCount());
// Depends on age, name and spouse (TestBean)
Object registered = lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertEquals(1, lbf.getBeanDefinitionCount());
DependenciesBean kerry = (DependenciesBean) registered;
TestBean rod = (TestBean) lbf.getBean("rod");
assertSame(rod, kerry.getSpouse());
}
/**
* <p>Constructor.</p>
* Useful for extending the store and relying on existing code
* to instantiate custom hibernate transaction.
*
* @param txManager Spring PlatformTransactionManager
* @param beanFactory Spring AutowireCapableBeanFactory
* @param entityManager EntityManager factory
* @param isScrollEnabled Whether or not scrolling is enabled on driver
* @param scrollMode Scroll mode to use for scrolling driver
* @param transactionSupplier Supplier for transaction
*/
protected SpringHibernateDataStore(PlatformTransactionManager txManager,
AutowireCapableBeanFactory beanFactory,
EntityManager entityManager,
ElideProperties elideProperties,
boolean isScrollEnabled,
ScrollMode scrollMode,
HibernateTransactionSupplier transactionSupplier) {
this.txManager = txManager;
this.beanFactory = beanFactory;
this.entityManager = entityManager;
this.elideProperties = elideProperties;
this.isScrollEnabled = isScrollEnabled;
this.scrollMode = scrollMode;
this.transactionSupplier = transactionSupplier;
}
protected void autowireContext(Action instance) {
AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
autowireBeanFactory.autowireBean(instance);
if (instance instanceof ApplicationContextAware) {
((ApplicationContextAware) instance).setApplicationContext(applicationContext);
}
if (instance instanceof InitializingBean) {
try {
((InitializingBean) instance).afterPropertiesSet();
} catch (Exception e) {
throw new RuntimeException(
"Unable to initialize UI Component - calling afterPropertiesSet for " +
instance.getClass(), e);
}
}
}
@Test
public void testAutowireBeanWithFactoryBeanByTypeWithPrimary() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd1 = new RootBeanDefinition(LazyInitFactory.class);
RootBeanDefinition bd2 = new RootBeanDefinition(LazyInitFactory.class);
bd2.setPrimary(true);
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
LazyInitFactory bd1FactoryBean = (LazyInitFactory) lbf.getBean("&bd1");
LazyInitFactory bd2FactoryBean = (LazyInitFactory) lbf.getBean("&bd2");
assertNotNull(bd1FactoryBean);
assertNotNull(bd2FactoryBean);
FactoryBeanDependentBean bean = (FactoryBeanDependentBean) lbf.autowire(FactoryBeanDependentBean.class,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertNotEquals(bd1FactoryBean, bean.getFactoryBean());
assertEquals(bd2FactoryBean, bean.getFactoryBean());
}
@Test
public void testAutowireBeanByTypeWithTwoMatches() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertTrue(ex.getMessage().contains("test"));
assertTrue(ex.getMessage().contains("spouse"));
}
}
@Test
public void testAutowireBeanByTypeWithTwoPrimaryCandidates() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPrimary(true);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
bd2.setPrimary(true);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertNotNull("Exception should have cause", ex.getCause());
assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass());
}
}
@Test
public void testAutowireBeanByTypeWithIdenticalPriorityCandidates() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
RootBeanDefinition bd = new RootBeanDefinition(HighPriorityTestBean.class);
RootBeanDefinition bd2 = new RootBeanDefinition(HighPriorityTestBean.class);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertNotNull("Exception should have cause", ex.getCause());
assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass());
assertTrue(ex.getMessage().contains("5")); // conflicting priority
}
}
public static final void setBlocking(ApplicationContext ctx, EndpointImpl impl) {
AutowireCapableBeanFactory fact = ctx.getAutowireCapableBeanFactory();
if (fact instanceof DefaultListableBeanFactory) {
DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory)fact;
for (BeanPostProcessor bpp : dlbf.getBeanPostProcessors()) {
if (CommonAnnotationBeanPostProcessor.class.isInstance(bpp)) {
impl.getServerFactory().setBlockPostConstruct(true);
impl.getServerFactory().setBlockInjection(false);
return;
}
if (bpp instanceof Jsr250BeanPostProcessor) {
impl.getServerFactory().setBlockInjection(true);
}
}
}
}
public static void main(String[] args) {
// 配置 XML 配置文件
// 启动 Spring 应用上下文
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-instantiation-context.xml");
// 通过 ApplicationContext 获取 AutowireCapableBeanFactory
AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
ServiceLoader<UserFactory> serviceLoader = beanFactory.getBean("userFactoryServiceLoader", ServiceLoader.class);
displayServiceLoader(serviceLoader);
// demoServiceLoader();
// 创建 UserFactory 对象,通过 AutowireCapableBeanFactory
UserFactory userFactory = beanFactory.createBean(DefaultUserFactory.class);
System.out.println(userFactory.createUser());
}
@Test
public void testAutowireWithSatisfiedJavaBeanDependency() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "Rod");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("rod", bd);
assertEquals(1, lbf.getBeanDefinitionCount());
// Depends on age, name and spouse (TestBean)
Object registered = lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertEquals(1, lbf.getBeanDefinitionCount());
DependenciesBean kerry = (DependenciesBean) registered;
TestBean rod = (TestBean) lbf.getBean("rod");
assertSame(rod, kerry.getSpouse());
}
private SpringContainedBean<?> createBean(
String name, Class<?> beanType, LifecycleOptions lifecycleOptions, BeanInstanceProducer fallbackProducer) {
try {
if (lifecycleOptions.useJpaCompliantCreation()) {
Object bean = this.beanFactory.autowire(beanType, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
this.beanFactory.autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
this.beanFactory.applyBeanPropertyValues(bean, name);
bean = this.beanFactory.initializeBean(bean, name);
return new SpringContainedBean<>(bean, beanInstance -> this.beanFactory.destroyBean(name, beanInstance));
}
else {
return new SpringContainedBean<>(this.beanFactory.getBean(name, beanType));
}
}
catch (BeansException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Falling back to Hibernate's default producer after bean creation failure for " +
beanType + ": " + ex);
}
return new SpringContainedBean<>(fallbackProducer.produceBeanInstance(name, beanType));
}
}
private <T> T resolveSchedulerBean(Class<T> schedulerType, boolean byName) {
if (byName) {
T scheduler = this.beanFactory.getBean(DEFAULT_TASK_SCHEDULER_BEAN_NAME, schedulerType);
if (this.beanFactory instanceof ConfigurableBeanFactory) {
((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(
DEFAULT_TASK_SCHEDULER_BEAN_NAME, this.beanName);
}
return scheduler;
}
else if (this.beanFactory instanceof AutowireCapableBeanFactory) {
NamedBeanHolder<T> holder = ((AutowireCapableBeanFactory) this.beanFactory).resolveNamedBean(schedulerType);
if (this.beanFactory instanceof ConfigurableBeanFactory) {
((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(
holder.getBeanName(), this.beanName);
}
return holder.getBeanInstance();
}
else {
return this.beanFactory.getBean(schedulerType);
}
}
protected void autowireContext(Component instance) {
AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
autowireBeanFactory.autowireBean(instance);
if (instance instanceof ApplicationContextAware) {
((ApplicationContextAware) instance).setApplicationContext(applicationContext);
}
if (instance instanceof InitializingBean) {
try {
((InitializingBean) instance).afterPropertiesSet();
} catch (Exception e) {
throw new RuntimeException(
"Unable to initialize Component - calling afterPropertiesSet for " +
instance.getClass());
}
}
}
protected void autowireContext(Renderer instance) {
AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
autowireBeanFactory.autowireBean(instance);
if (instance instanceof ApplicationContextAware) {
((ApplicationContextAware) instance).setApplicationContext(applicationContext);
}
if (instance instanceof InitializingBean) {
try {
((InitializingBean) instance).afterPropertiesSet();
} catch (Exception e) {
throw new RuntimeException("Unable to initialize Renderer - calling afterPropertiesSet for " +
instance.getClass(), e);
}
}
}
@Test
public void testAutowireWithTwoMatchesForConstructorDependency() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("rod", bd);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("rod2", bd2);
try {
lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertTrue(ex.getMessage().contains("rod"));
assertTrue(ex.getMessage().contains("rod2"));
}
}
public MtasUimaParser(MtasConfiguration config)
{
super(config);
// Perform dependency injection
AutowireCapableBeanFactory factory = ApplicationContextProvider.getApplicationContext()
.getAutowireCapableBeanFactory();
factory.autowireBean(this);
factory.initializeBean(this, "transientParser");
JSONObject jsonParserConfiguration = new JSONObject(
config.attributes.get(ARGUMENT_PARSER_ARGS));
MtasDocumentIndex index = MtasDocumentIndex
.getIndex(jsonParserConfiguration.getLong(PARAM_PROJECT_ID));
// Initialize and populate the hash maps for the layers and features
for (AnnotationFeature feature : index.getFeaturesToIndex()) {
layers.put(feature.getLayer().getName(), feature.getLayer());
layerFeatures
.computeIfAbsent(feature.getLayer().getName(), key -> new ArrayList<>())
.add(feature);
}
}
@Test
public void testAutowireBeanByTypeWithTwoMatches() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertTrue(ex.getMessage().contains("test"));
assertTrue(ex.getMessage().contains("spouse"));
}
}
private ProjectExportTaskHandle startTask(ProjectExportTask_ImplBase aTask)
{
ProjectExportTaskHandle handle = aTask.getHandle();
// This autowires the task fields manually.
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(aTask);
factory.initializeBean(aTask, "transientTask");
tasks.put(handle, new TaskInfo(taskExecutorService.submit(aTask), aTask));
return handle;
}
@Test
public void testAutowireExistingBeanByType() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("test", bd);
DependenciesBean existingBean = new DependenciesBean();
lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
TestBean test = (TestBean) lbf.getBean("test");
assertEquals(existingBean.getSpouse(), test);
}
@Test
public void testAutowireBeanByType() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("test", bd);
DependenciesBean bean = (DependenciesBean)
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
TestBean test = (TestBean) lbf.getBean("test");
assertEquals(test, bean.getSpouse());
}
@Override
public void registerClient(String clientAddress) {
System.out.println("Client from " + clientAddress);
ApplicationContext context = ServerApp.getApplicationContext();
AutowireCapableBeanFactory factory = context
.getAutowireCapableBeanFactory();
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(RmiProxyFactoryBean.class);
beanDefinition.setAutowireCandidate(true);
Class<EM> entityModelInterfaceClass = getEntityModelInterfaceClass();
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.addPropertyValue("serviceInterface",
entityModelInterfaceClass);
propertyValues.addPropertyValue("serviceUrl", "rmi://" + clientAddress
+ ":1099/" + entityModelInterfaceClass.getCanonicalName());
beanDefinition.setPropertyValues(propertyValues);
registry.registerBeanDefinition(
entityModelInterfaceClass.getCanonicalName(), beanDefinition);
EM entityModel = context.getBean(entityModelInterfaceClass);
registerEntityModel(entityModel);
System.out.println(entityModel);
}
@Test
public void testAutowireBeanByTypeWithNoDependencyCheck() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
DependenciesBean bean = (DependenciesBean)
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
assertNull(bean.getSpouse());
}
@Override
public void run()
{
try {
while (!Thread.interrupted()) {
log.debug("Waiting for new indexing task...");
activeTask = queue.take();
try {
AutowireCapableBeanFactory factory = applicationContext
.getAutowireCapableBeanFactory();
factory.autowireBean(activeTask);
factory.initializeBean(activeTask, "transientTask");
log.debug("Indexing task started: {}", activeTask);
activeTask.run();
log.debug("Indexing task completed: {}", activeTask);
}
// Catching Throwable is intentional here as we want to continue the execution even
// if a particular recommender fails.
catch (Throwable e) {
log.error("Indexing task failed: {}", activeTask, e);
}
finally {
activeTask = null;
}
}
}
catch (InterruptedException ie) {
log.info("Thread interrupted: ", ie);
}
}
@Override
public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException {
NamedBeanHolder<T> namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false);
if (namedBean != null) {
return namedBean;
}
BeanFactory parent = getParentBeanFactory();
if (parent instanceof AutowireCapableBeanFactory) {
return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType);
}
throw new NoSuchBeanDefinitionException(requiredType);
}
private AdminUserDAO getAdminUserDAO( )
{
AdminUserDAO adminUserDAO = new AdminUserDAO( );
ApplicationContext context = SpringContextService.getContext( );
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory( );
beanFactory.autowireBean( adminUserDAO );
return adminUserDAO;
}
private AdminUserDAO getAdminUserDAO( )
{
AdminUserDAO adminUserDAO = new AdminUserDAO( );
ApplicationContext context = SpringContextService.getContext( );
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory( );
beanFactory.autowireBean( adminUserDAO );
return adminUserDAO;
}
@Test
public void testAutowireWithSatisfiedConstructorDependency() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "Rod");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("rod", bd);
assertEquals(1, lbf.getBeanDefinitionCount());
Object registered = lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
assertEquals(1, lbf.getBeanDefinitionCount());
ConstructorDependency kerry = (ConstructorDependency) registered;
TestBean rod = (TestBean) lbf.getBean("rod");
assertSame(rod, kerry.spouse);
}