Java Code Examples for org.springframework.beans.factory.BeanFactory#getBean()

The following examples show how to use org.springframework.beans.factory.BeanFactory#getBean() . 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: AdvisorAutoProxyCreatorIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testRollbackRulesOnMethodPreventRollback() throws Exception {
	BeanFactory bf = getBeanFactory();
	Rollback rb = (Rollback) bf.getBean("rollback");

	CallCountingTransactionManager txMan = (CallCountingTransactionManager) bf.getBean(TXMANAGER_BEAN_NAME);

	assertEquals(0, txMan.commits);
	// Should NOT roll back on ServletException
	try {
		rb.echoException(new ServletException());
	}
	catch (ServletException ex) {

	}
	assertEquals("Transaction counts match", 1, txMan.commits);
}
 
Example 2
Source File: NettyEmbeddedAutoConfiguration.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
 * Add a TCP service factory
 * @param protocolHandlers protocolHandlers
 * @param serverListeners serverListeners
 * @param beanFactory beanFactory
 * @return NettyTcpServerFactory
 */
@Bean("nettyServerFactory")
@ConditionalOnMissingBean(NettyTcpServerFactory.class)
public NettyTcpServerFactory nettyTcpServerFactory(Collection<ProtocolHandler> protocolHandlers,
                                                   Collection<ServerListener> serverListeners,
                                                   BeanFactory beanFactory){
    Supplier<DynamicProtocolChannelHandler> handlerSupplier = ()->{
        Class<?extends DynamicProtocolChannelHandler> type = nettyProperties.getChannelHandler();
        return type == DynamicProtocolChannelHandler.class?
                new DynamicProtocolChannelHandler() : beanFactory.getBean(type);
    };
    NettyTcpServerFactory tcpServerFactory = new NettyTcpServerFactory(nettyProperties,handlerSupplier);
    tcpServerFactory.getProtocolHandlers().addAll(protocolHandlers);
    tcpServerFactory.getServerListeners().addAll(serverListeners);
    return tcpServerFactory;
}
 
Example 3
Source File: BeanFactoryAnnotationUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a
 * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given
 * qualifier, or having a bean name matching the given qualifier.
 * @param beanFactory the BeanFactory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 * @throws NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found
 * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 * @throws BeansException if the bean could not be created
 * @see BeanFactory#getBean(Class)
 */
public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier)
		throws BeansException {

	Assert.notNull(beanFactory, "BeanFactory must not be null");

	if (beanFactory instanceof ConfigurableListableBeanFactory) {
		// Full qualifier matching supported.
		return qualifiedBeanOfType((ConfigurableListableBeanFactory) beanFactory, beanType, qualifier);
	}
	else if (beanFactory.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name.
		return beanFactory.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for bean name '" + qualifier +
				"'! (Note: Qualifier matching not supported because given " +
				"BeanFactory does not implement ConfigurableListableBeanFactory.)");
	}
}
 
Example 4
Source File: SpringBeanELResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setValue(ELContext elContext, Object base, Object property, Object value) throws ELException {
	if (base == null) {
		String beanName = property.toString();
		BeanFactory bf = getBeanFactory(elContext);
		if (bf.containsBean(beanName)) {
			if (value == bf.getBean(beanName)) {
				// Setting the bean reference to the same value is alright - can simply be ignored...
				elContext.setPropertyResolved(true);
			}
			else {
				throw new PropertyNotWritableException(
						"Variable '" + beanName + "' refers to a Spring bean which by definition is not writable");
			}
		}
	}
}
 
Example 5
Source File: BeanInstantiationDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 配置 XML 配置文件
    // 启动 Spring 应用上下文
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean-instantiation-context.xml");
    User user = beanFactory.getBean("user-by-static-method", User.class);
    User userByInstanceMethod = beanFactory.getBean("user-by-instance-method", User.class);
    User userByFactoryBean = beanFactory.getBean("user-by-factory-bean", User.class);
    System.out.println(user);
    System.out.println(userByInstanceMethod);
    System.out.println(userByFactoryBean);

    System.out.println(user == userByInstanceMethod);
    System.out.println(user == userByFactoryBean);

}
 
Example 6
Source File: AbstractAutoProxyCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Resolves the specified interceptor names to Advisor objects.
 * @see #setInterceptorNames
 */
private Advisor[] resolveInterceptorNames() {
	BeanFactory bf = this.beanFactory;
	ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
	List<Advisor> advisors = new ArrayList<>();
	for (String beanName : this.interceptorNames) {
		if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
			Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
			Object next = bf.getBean(beanName);
			advisors.add(this.advisorAdapterRegistry.wrap(next));
		}
	}
	return advisors.toArray(new Advisor[0]);
}
 
Example 7
Source File: ConfigurationClassProcessingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void configurationWithPrototypeScopedBeans() {
	BeanFactory factory = initBeanFactory(ConfigWithPrototypeBean.class);

	TestBean foo = factory.getBean("foo", TestBean.class);
	ITestBean bar = factory.getBean("bar", ITestBean.class);
	ITestBean baz = factory.getBean("baz", ITestBean.class);

	assertSame(foo.getSpouse(), bar);
	assertNotSame(bar.getSpouse(), baz);
}
 
Example 8
Source File: BeanFactoryWithClassPathResourceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void createBeanFactoryAndCheckEmployeeBean() {
    Resource res = new ClassPathResource("beanfactory-example.xml");
    BeanFactory factory = new XmlBeanFactory(res);
    Employee emp = (Employee) factory.getBean("employee");

    assertTrue(factory.isSingleton("employee"));
    assertTrue(factory.getBean("employee") instanceof Employee);
    assertTrue(factory.isTypeMatch("employee", Employee.class));
    assertTrue(factory.getAliases("employee").length > 0);
}
 
Example 9
Source File: SpringTransactionManagerContextInjectionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testBeanInjectionUsingConfig() throws Exception {
    BeanFactory factory = new AnnotationConfigApplicationContext(TestCfgConfiguration.class);

    TestInjectionLifecycleBean bean1 = (TestInjectionLifecycleBean)factory.getBean("bean1");
    TestInjectionLifecycleBean bean2 = (TestInjectionLifecycleBean)factory.getBean("bean2");

    bean1.checkState();
    bean2.checkState();
}
 
Example 10
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * If no pointcuts match (no attrs) there should be proxying.
 */
@Test
public void testNoProxy() throws Exception {
	BeanFactory bf = getBeanFactory();
	Object o = bf.getBean("noSetters");
	assertFalse(AopUtils.isAopProxy(o));
}
 
Example 11
Source File: SpringBeanELResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(ELContext elContext, Object base, Object property) throws ELException {
	if (base == null) {
		String beanName = property.toString();
		BeanFactory bf = getBeanFactory(elContext);
		if (bf.containsBean(beanName)) {
			if (logger.isTraceEnabled()) {
				logger.trace("Successfully resolved variable '" + beanName + "' in Spring BeanFactory");
			}
			elContext.setPropertyResolved(true);
			return bf.getBean(beanName);
		}
	}
	return null;
}
 
Example 12
Source File: AdvisorAutoProxyCreatorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * We have custom TargetSourceCreators but there's no match, and
 * hence no proxying, for this bean
 */
@Test
public void testCustomTargetSourceNoMatch() throws Exception {
	BeanFactory bf = new ClassPathXmlApplicationContext(CUSTOM_TARGETSOURCE_CONTEXT, CLASS);
	ITestBean test = (ITestBean) bf.getBean("test");
	assertFalse(AopUtils.isAopProxy(test));
	assertEquals("Rod", test.getName());
	assertEquals("Kerry", test.getSpouse().getName());
}
 
Example 13
Source File: BeanAliasDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 配置 XML 配置文件
    // 启动 Spring 应用上下文
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean-definitions-context.xml");
    // 通过别名 xiaomage-user 获取曾用名 user 的 bean
    User user = beanFactory.getBean("user", User.class);
    User xiaomageUser = beanFactory.getBean("xiaomage-user", User.class);
    System.out.println("xiaomage-user 是否与 user Bean 相同:" + (user == xiaomageUser));
}
 
Example 14
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
	NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args);
	if (namedBean != null) {
		return namedBean.getBeanInstance();
	}
	BeanFactory parent = getParentBeanFactory();
	if (parent != null) {
		return parent.getBean(requiredType, args);
	}
	throw new NoSuchBeanDefinitionException(requiredType);
}
 
Example 15
Source File: AppInfoMigrationPlugin.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Inject
public AppInfoMigrationPlugin( EntityManagerFactory emf, MigrationInfoSerialization migrationInfoSerialization,
                               EntityCollectionManagerFactory entityCollectionManagerFactory,
                               GraphManagerFactory graphManagerFactory, BeanFactory beanFactory ) {

    this.emf = emf;
    this.migrationInfoSerialization = migrationInfoSerialization;
    this.entityCollectionManagerFactory = entityCollectionManagerFactory;
    this.graphManagerFactory = graphManagerFactory;
    this.managementService = beanFactory.getBean( ManagementService.class );
}
 
Example 16
Source File: ConfigurationClassProcessingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void configurationWithNullReference() {
	BeanFactory factory = initBeanFactory(ConfigWithNullReference.class);

	TestBean foo = factory.getBean("foo", TestBean.class);
	assertTrue(factory.getBean("bar").equals(null));
	assertNull(foo.getSpouse());
}
 
Example 17
Source File: SpringBeanELResolver.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(ELContext elContext, Object base, Object property) throws ELException {
	if (base == null) {
		String beanName = property.toString();
		BeanFactory bf = getBeanFactory(elContext);
		if (bf.containsBean(beanName)) {
			if (logger.isTraceEnabled()) {
				logger.trace("Successfully resolved variable '" + beanName + "' in Spring BeanFactory");
			}
			elContext.setPropertyResolved(true);
			return bf.getBean(beanName);
		}
	}
	return null;
}
 
Example 18
Source File: SpringDriverTest.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
public void test() throws SQLException, ClassNotFoundException, EtlExecutorException {
    BeanFactory bf = new ClassPathXmlApplicationContext("scriptella/driver/spring/springbeans.xml");
    DataSource ds = (DataSource) bf.getBean("datasource"); //Test if bean factory contain correct data
    Connection con = ds.getConnection();
    con.createStatement().executeQuery("select * from AutoStart"); //A table should be created on startup
    EtlExecutor exec = (EtlExecutor) bf.getBean("executor");
    exec.execute();
    con.createStatement().executeQuery("select * from SpringTable"); //A table should be created
    //Test batched executor
    ResultSet rs = con.createStatement().executeQuery("select * from Batch order by id");//A table should be created
    assertTrue(rs.next());
    assertEquals(1, rs.getInt(1));
    assertFalse(rs.next());
    con.createStatement().execute("SHUTDOWN");
}
 
Example 19
Source File: AdvisorAutoProxyCreatorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPrototypeTargetSource() throws Exception {
	CountingTestBean.count = 0;
	BeanFactory bf = new ClassPathXmlApplicationContext(CUSTOM_TARGETSOURCE_CONTEXT, CLASS);
	ITestBean test = (ITestBean) bf.getBean("prototypeTest");
	assertTrue(AopUtils.isAopProxy(test));
	Advised advised = (Advised) test;
	assertTrue(advised.getTargetSource() instanceof PrototypeTargetSource);
	assertEquals("Rod", test.getName());
	// Check that references survived prototype creation
	assertEquals("Kerry", test.getSpouse().getName());
	assertEquals("Only 2 CountingTestBeans instantiated", 2, CountingTestBean.count);
	CountingTestBean.count = 0;
}
 
Example 20
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testTxIsProxied() throws Exception {
	BeanFactory bf = getBeanFactory();
	ITestBean test = (ITestBean) bf.getBean("test");
	assertTrue(AopUtils.isAopProxy(test));
}