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

The following are Jave code examples for showing how to use getBean() of the org.springframework.beans.factory.BeanFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: X-mall   File: MallInterceptor.java   Source Code and License Vote up 6 votes
/**
 * 保存 XmallContext 信息
 *
 * @param request
 */
private void saveXmallContext(HttpServletRequest request) {
    // 1.从 request 的 Header 头中读出 token
    String token = request.getHeader(XMALL_TOKEN);
    if (StringUtils.isBlank(token)) {
        logger.error("===> Request Header no token : xmall-Token");
        return;
    }
    logger.info("===> xmall-Token : {}", token);

    if (iUserService == null) { //解决service为null无法注入问题
        logger.error("===> iUserService is null!!!");
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        iUserService = (IUserService) factory.getBean("iUserService");
    }

    // 2.将 token 取出 user 登录对象
    ServerResponse<User> response = iUserService.getUser(token);
    if (response.isSuccess()) {
        User user = response.getData();
        // 3.将 user 对象写入 context
        XmallContext context = XmallContext.getContext();
        context.setLoginUser(user);
    }
}
 
Example 2
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: UserForm.java   Source Code and License Vote up 6 votes
private void jTable1FocusGained(java.awt.event.FocusEvent evt) {
BeanFactory factory = new DataBaseDataSource().getDataFactory();
 registrationDAO = (RegistrationDAO) factory
		.getBean("registrationDAO");
jList1.setModel(new javax.swing.AbstractListModel() {
	String[] strings = registrationDAO.viewFileName(users.getUserid()).split(",");

	public int getSize() {
		return strings.length;
	}

	public Object getElementAt(int i) {
		return strings[i];
	}
});
jScrollPane2.setViewportView(jList1);	}
 
Example 3
Project: lams   File: BeanFactoryAnnotationUtils.java   Source Code and License Vote up 6 votes
/**
 * 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 NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 */
public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier) {
	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
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: UserForm.java   Source Code and License Vote up 6 votes
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
	BeanFactory factory = new DataBaseDataSource().getDataFactory();
	registrationDAO = (RegistrationDAO) factory.getBean("registrationDAO");
	Object obj[][] = registrationDAO.viewCloudFiles(users.getUserid());
	Object string[] = registrationDAO.viewCloudMetaData();
	new CloudServerWindow().setVisible(true);

	jList1.setModel(new javax.swing.AbstractListModel() {
		String[] strings = registrationDAO.viewFileName(users.getUserid())
				.split(",");

		public int getSize() {
			return strings.length;
		}

		public Object getElementAt(int i) {
			return strings[i];
		}
	});
}
 
Example 5
Project: lams   File: SpringBeanELResolver.java   Source Code and License Vote up 6 votes
@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 6
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: GroupMemberchange.java   Source Code and License Vote up 6 votes
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
	String groupname = jComboBox1.getSelectedItem().toString();
	if (!groupname.equals(users.getGroupname())) {
		BeanFactory beanFactory = new DataBaseDataSource().getDataFactory();
		RegistrationDAO registrationDAO = (RegistrationDAO) beanFactory
				.getBean("registrationDAO");
		users.setNewgroupname(groupname);
		System.out.println(groupname);
		boolean b = registrationDAO.usergroupcount(users);
		File f = new File("groups");
		boolean delete = f.delete();
		System.out.println("file deleted " + delete);
		new GroupMemberchange(users).setVisible(true);

	} else {

	}

}
 
Example 7
Project: alfresco-repository   File: DynamicSolrStoreMappingWrapperFactory.java   Source Code and License Vote up 5 votes
/**
 * @param slice
 * @param beanFactory
 * @return
 */
public static SolrStoreMappingWrapper wrap(List<ShardInstance> slice, BeanFactory beanFactory)
{
    HttpClientFactory httpClientFactory = (HttpClientFactory)beanFactory.getBean("solrHttpClientFactory");
    for(ShardInstance instance : slice)
    {
        Pair<String, Integer> key = new Pair<String, Integer>(instance.getHostName(), instance.getPort());
        if(!clients.contains(key))
        {
            clients.put(key, httpClientFactory.getHttpClient(key.getFirst(), key.getSecond()));
        }
    }
    
    return new DynamicSolrStoreMappingWrapper(slice);
}
 
Example 8
Project: lams   File: CommonAnnotationBeanPostProcessor.java   Source Code and License Vote up 5 votes
/**
 * Obtain a resource object for the given name and type through autowiring
 * based on the given factory.
 * @param factory the factory to autowire against
 * @param element the descriptor for the annotated field/method
 * @param requestingBeanName the name of the requesting bean
 * @return the resource object (never {@code null})
 * @throws BeansException if we failed to obtain the target resource
 */
protected Object autowireResource(BeanFactory factory, LookupElement element, String requestingBeanName)
		throws BeansException {

	Object resource;
	Set<String> autowiredBeanNames;
	String name = element.name;

	if (this.fallbackToDefaultTypeMatch && element.isDefaultName &&
			factory instanceof AutowireCapableBeanFactory && !factory.containsBean(name)) {
		autowiredBeanNames = new LinkedHashSet<String>();
		resource = ((AutowireCapableBeanFactory) factory).resolveDependency(
				element.getDependencyDescriptor(), requestingBeanName, autowiredBeanNames, null);
	}
	else {
		resource = factory.getBean(name, element.lookupType);
		autowiredBeanNames = Collections.singleton(name);
	}

	if (factory instanceof ConfigurableBeanFactory) {
		ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
		for (String autowiredBeanName : autowiredBeanNames) {
			if (beanFactory.containsBean(autowiredBeanName)) {
				beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
			}
		}
	}

	return resource;
}
 
Example 9
Project: holon-datastore-jpa   File: JpaEntityScanPackages.java   Source Code and License Vote up 5 votes
/**
 * Return the {@link JpaEntityScanPackages} for the given bean factory.
 * @param beanFactory the source bean factory
 * @param dataContextId Data context id
 * @return the {@link JpaEntityScanPackages} for the bean factory (never {@code null})
 */
public static JpaEntityScanPackages get(BeanFactory beanFactory, String dataContextId) {
	try {
		return beanFactory.getBean(buildBeanName(dataContextId), JpaEntityScanPackages.class);
	} catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException ex) {
		return NONE;
	}
}
 
Example 10
Project: holon-core   File: TenantScope.java   Source Code and License Vote up 5 votes
/**
 * Get the {@link TenantResolver} to use from context
 * @return TenantResolver
 */
private TenantResolver getTenantResolver() {
	BeanFactory factory = beanFactory.get();
	if (factory == null) {
		throw new IllegalStateException("A beanFactory is not available");
	}
	return factory.getBean(TenantResolver.class);
}
 
Example 11
Project: spring-data-jdbc-template   File: BeanFactoryUtils.java   Source Code and License Vote up 5 votes
public static <T> T getBeanByNameOrType(BeanFactory beanFactory, String name, Class<T> requiredType) {
    if (StringUtils.isEmpty(name)) {
        return beanFactory.getBean(requiredType);
    } else {
        return beanFactory.getBean(name, requiredType);
    }
}
 
Example 12
Project: rure   File: UserServiceTest.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    String[] resources = new String[]{"classpath*:applicationContext-dubbo-consumer.xml"};
    BeanFactory factory = new ClassPathXmlApplicationContext(resources);
    UserService userService = (UserService)factory.getBean("userService");
    UserExample userExample = new UserExample();
    userExample.createCriteria().andIdEqualTo("lisi");
    List<User> list = userService.selectByExample(userExample);
    for (User bean: list) {
        System.out.println(bean.toString());
    }
}
 
Example 13
Project: rure   File: DemoUserServiceTest.java   Source Code and License Vote up 5 votes
@Test
public void ceshi(){
    DemoUser user = new DemoUser();
    user.setUsername("abc");
    user.setPassword(MD5Util.MD5("abc"));
    user.setSex(1);
    user.setCrtime(StringUtil.Date2String());

    String[] resources = new String[]{"classpath*:/dubbo-consumer.xml"  ,"classpath*:/META-INF/spring/applicationContext-jdbc.xml"};
    BeanFactory factory = new ClassPathXmlApplicationContext(resources);
    demoUserService = (DemoUserService)factory.getBean("demoUserService");
    DemoUser result = demoUserService.createUser(user);
    System.out.println(result);
}
 
Example 14
Project: rure   File: DemoMain.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    String[] resources = new String[]{"classpath*:/spring-dubbo-consumer.xml"};
    BeanFactory factory = new ClassPathXmlApplicationContext(resources);
    DemoUserService demoUserService = (DemoUserService)factory.getBean("demoUserService");
    int result = demoUserService.selectDemoUserCount();
    System.out.println(result);
}
 
Example 15
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: MainFrame.java   Source Code and License Vote up 5 votes
/** Creates new form MainFrame */
public MainFrame() {
	BeanFactory beanFactory = new DataBaseDataSource().getDataFactory();
	registrationDAO = (RegistrationDAO) beanFactory
			.getBean("registrationDAO");
	initComponents();
}
 
Example 16
Project: springboot_op   File: LoggerInterceptor.java   Source Code and License Vote up 4 votes
private <T> T getDAO(Class<T> clazz,HttpServletRequest request)
{
    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    return factory.getBean(clazz);
}
 
Example 17
Project: ontology_setting   File: LoggerInterceptor.java   Source Code and License Vote up 4 votes
private <T> T getDAO(Class<T> clazz,HttpServletRequest request)
{
    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    return factory.getBean(clazz);
}
 
Example 18
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: CloudServerWindow.java   Source Code and License Vote up 4 votes
/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
	BeanFactory factory = new DataBaseDataSource().getDataFactory();
	registrationDAO = (RegistrationDAO) factory.getBean("registrationDAO");
	
	jLabel1 = new javax.swing.JLabel();
	jScrollPane1 = new javax.swing.JScrollPane();
	jTable1 = new javax.swing.JTable();

	setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
	setTitle("CloudServerWindow");

	jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
	jLabel1.setForeground(new java.awt.Color(255, 0, 0));
	jLabel1.setText("Cloud Server Uploaded Files");

	Object obj[][] = registrationDAO.viewCloudFiles();
	Object string[] = registrationDAO.viewCloudMetaData();
	jTable1.setModel(new javax.swing.table.DefaultTableModel(obj, string));
	jScrollPane1.setViewportView(jTable1);

	


	javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
			getContentPane());
	getContentPane().setLayout(layout);
	layout.setHorizontalGroup(layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			layout.createSequentialGroup().addGap(335, 335, 335)
					.addComponent(jLabel1).addContainerGap(286,
							Short.MAX_VALUE)).addGroup(
			javax.swing.GroupLayout.Alignment.TRAILING,
			layout.createSequentialGroup().addContainerGap(18,
					Short.MAX_VALUE).addComponent(jScrollPane1,
					javax.swing.GroupLayout.PREFERRED_SIZE, 909,
					javax.swing.GroupLayout.PREFERRED_SIZE).addGap(27, 27,
					27)));
	layout.setVerticalGroup(layout.createParallelGroup(
			javax.swing.GroupLayout.Alignment.LEADING).addGroup(
			layout.createSequentialGroup().addGap(38, 38, 38).addComponent(
					jLabel1).addGap(18, 18, 18).addComponent(jScrollPane1,
					javax.swing.GroupLayout.PREFERRED_SIZE,
					javax.swing.GroupLayout.DEFAULT_SIZE,
					javax.swing.GroupLayout.PREFERRED_SIZE)
					.addContainerGap(104, Short.MAX_VALUE)));

	pack();
}
 
Example 19
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: ViewGroupMembers.java   Source Code and License Vote up 3 votes
/** Creates new form ViewGroupMembers */
public ViewGroupMembers() {
	
	BeanFactory beanFactory=new DataBaseDataSource().getDataFactory();
	RegistrationDAO registrationDAO=(RegistrationDAO)beanFactory.getBean("registrationDAO");
	
	boolean b=registrationDAO.viewGroupMembers();
	
	
	initComponents();
}
 
Example 20
Project: lams   File: BeanFactoryRefreshableTargetSource.java   Source Code and License Vote up 2 votes
/**
 * A template method that subclasses may override to provide a
 * fresh target object for the given bean factory and bean name.
 * <p>This default implementation fetches a new target bean
 * instance from the bean factory.
 * @see org.springframework.beans.factory.BeanFactory#getBean
 */
protected Object obtainFreshBean(BeanFactory beanFactory, String beanName) {
	return beanFactory.getBean(beanName);
}