一个简单的JavaBean==>Something.Java
package com.springl.bean;
import java.util.Date;
public class Something {
private Integer id;
private Date createTime;
private Date updateTime;
public Something() {
System.out.println("==============>Something[Constructor]");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "Something{" +
"id=" + id +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
一个配置类
package com.springl.bean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Date;
@Configuration
public class BeanCreateConfig {
@Bean
public Something something(){
Date now = new Date();
Something something = new Something();
something.setId(1);
something.setCreateTime(now);
something.setUpdateTime(now);
return something;
}
}
一个测试类
package com.springl.test;
import com.springl.bean.BeanCreateConfig;
import com.springl.bean.Something;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BeanCreateTest {
@Test
public void testBean(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanCreateConfig.class);
Something something = (Something) applicationContext.getBean("something");
System.out.println(something);
applicationContext.close();
}
}
最终测试结果:
==============>Something[Constructor]
Something{id=1, createTime=Fri Feb 07 22:18:47 EST 2020, updateTime=Fri Feb 07 22:18:47 EST 2020}
下边看下这个Bean到底是怎么创建出来的
在[Something.Java]构造函数上打上断点,总体看下执行的流程
1.在配置类中创建AnnotationConfigApplicationContext对象时,执行其构造函数
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanCreateConfig.class);
看下AnnotationConfigApplicationContext对象的构造函数
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
//创建AnnotationConfigApplicationContext对象的时候执行到这里
refresh();
}
2.执行AnnotationConfigApplicationContext.refresh();------->AbstractApplicationContext.refresh();
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//执行到这里,初始化所有剩下的非懒加载的单实例对象
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
3.继续执行AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory);//初始化剩下的非懒加载的单例对象
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//执行到这里,初始化所有剩下的非懒加载的单实例对象
beanFactory.preInstantiateSingletons();
}
4.继续执行beanFactory.preInstantiateSingletons(); 在这里的beanFactory是DefaultListableBeanFactory的对象
@Override
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//不是抽象类,并且是单实例bean,并且不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
isEagerInit = (