主要有兩種方式:
專業(yè)從事成都網(wǎng)站設計、做網(wǎng)站,高端網(wǎng)站制作設計,小程序開發(fā),網(wǎng)站推廣的成都做網(wǎng)站的公司。優(yōu)秀技術團隊竭力真誠服務,采用html5+CSS3前端渲染技術,成都響應式網(wǎng)站建設,讓網(wǎng)站在手機、平板、PC、微信下都能呈現(xiàn)。建站過程建立專項小組,與您實時在線互動,隨時提供解決方案,暢聊想法和感受。
1.通過實現(xiàn)InitializingBean接口的afterPropertiesSet()方法,在方法中處理業(yè)務
2.在配置文件中配置init-method
實現(xiàn)方式1:InitializingBean
@Component
public class InitializingMyBean implements InitializingBean {
? ? @Autowired
private UserRepository userRepository;
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("》》》新增用戶《《《 ");
User user =new User();
user.setName("admin");
user.setPassword("admin123");
user.setAge("23");
user.setSex("男");
User add? = userRepository.save(user);
if(!StringUtils.isEmpty(add)){
System.out.println("新增用戶成功!");
}else{
System.out.println("新增用戶失敗!");
}
}
?
?
}
2.配置文件 :init-method
xml version="1.0" encoding="UTF-8"?>DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"> ?init-method="init">bean>beans> 3.兩種方式的區(qū)別: 實現(xiàn)InitializingBean接口是直接調用afterPropertiesSet方法,比通過反射調用init-method指定的方法效率相對來說要高點。但是init-method方式消除了對spring的依賴 4.注意:如果在spring初始化bean的時候,如果該bean是實現(xiàn)了InitializingBean接口,并且同時在配置文件中指定了init- method, ?* 系統(tǒng)則是先調用afterPropertiesSet方法,然后在調用init-method中指定的方法 5.InitializingBean和init-mthod同時執(zhí)行的原理: 詳見:org.springframework.beans.factory.support包下的抽象類AbstractAutowireCapableBeanFactory 主要處理代碼如下: /** * Give a bean a chance to react now all its properties are set, * and a chance to know about its owning bean factory (this object). * This means checking whether the bean implements InitializingBean or defines * a custom init method, and invoking the necessary callback(s) if it does. * @param beanName the bean name in the factory (for debugging purposes) * @param bean the new bean instance we may need to initialize * @param mbd the merged bean definition that the bean was created with * (can also be {@code null}, if given an existing bean instance) * @throws Throwable if thrown by init methods or by the invocation process * @see #invokeCustomInitMethod */ protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { ? ? ? ? ? ? //獲取當前bean是否實現(xiàn)了InitializingMyBean接口,如果實現(xiàn)了就執(zhí)行afterPropertiesSet方法 boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isDebugEnabled()) { logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction @Override public Object run() throws Exception { //調用afterPropertiesSet() ((InitializingBean) bean).afterPropertiesSet(); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //調用afterPropertiesSet() ((InitializingBean) bean).afterPropertiesSet(); } } ? ? ? ? ? ? //如果在配置文件中設置了init-mthod屬性就通過反射調用init-method指定的方法 if (mbd != null) { String initMethodName = mbd.getInitMethodName(); if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } } } /** * Invoke the specified custom init method on the given bean. * Called by invokeInitMethods. * Can be overridden in subclasses for custom resolution of init * methods with arguments. * @see #invokeInitMethods */ protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { String initMethodName = mbd.getInitMethodName(); final Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); if (initMethod == null) { if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Couldn't find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { if (logger.isDebugEnabled()) { logger.debug("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } } ? if (logger.isDebugEnabled()) { logger.debug("Invoking init method? '" + initMethodName + "' on bean with name '" + beanName + "'"); } ? if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedExceptionAction @Override public Object run() throws Exception { ReflectionUtils.makeAccessible(initMethod); return null; } }); try { AccessController.doPrivileged(new PrivilegedExceptionAction @Override public Object run() throws Exception { initMethod.invoke(bean); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { ReflectionUtils.makeAccessible(initMethod); initMethod.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
分享題目:Spring依賴注入后行為實現(xiàn)
鏈接地址:http://weahome.cn/article/gehihj.html