Spring BeanDefinition元信息定义方式
Bean Definition是一个包含Bean元数据的对象。它描述了如何创建Bean实例、Bean属性的值以及Bean之间的依赖关系。可以使用多种方式来定义 Bean Definition 元信息,包括:
除此之外,还可以通过实现
BeanDefinitionRegistryPostProcessor 接口来自定义 Bean Definition 的生成过程。这个接口有一个方法 postProcessBeanDefinitionRegistry(),允许开发人员动态地添加、修改或删除Bean Definition元信息。
<bean id="user" class="org.thinging.in.spring.ioc.overview.domAIn.User">
<property name="id" value="1"/>
<property name="name" value="Liutx"/>
</bean>
@Service(value = "HelloService")
public class HelloService {
private final Logger logger = LoggerFactory.getLogger(HelloService.class);
private final HelloAsyncService helloAsyncService;
public HelloService(HelloAsyncService helloAsyncService) {
this.helloAsyncService = helloAsyncService;
}
}
value = "HelloService" 即为Bean:HelloService的元数据,在构造方法中的依赖关系同样属于元数据。
@Component(value = "balanceredisProcessor")
public class BalanceRedisProcessorService implements EntryHandler<Balance>, Runnable {
@Autowired(required = true)
public BalanceRedisProcessorService(RedisUtils redisUtils,
CanalConfig canalConfig,
@Qualifier("ownThreadPoolExecutor") Executor executor, RocketMQProducer rocketMqProducer) {
this.redisUtils = redisUtils;
this.canalConfig = canalConfig;
this.executor = executor;
this.rocketMQProducer = rocketMqProducer;
}
}
@Component(value = "balanceRedisProcessor") 是
Bean:BalanceRedisProcessorService的元数据,在构造方法中的依赖关系同样属于元数据。
在Spring中,无论是通过XML、注解、Java配置类定义Bean元数据,最终都是需要转换成BeanDefinition对象,然后被注册到Spring容器中。
而BeanDefinition的创建过程,确实是通过AbstractBeanDefinition及其派生类、``等一系列工具类实现的。
将xml文件中的配置转为为BeanDefinition需要依赖自XmlBeanDefinitionReader类中的loadBeanDefinitions方法。
选自:Spring Framework 5.2.20 RELEASE版本的XmlBeanDefinitionReader。
private final ThreadLocal<Set<EncodedResource>> resourcesCurrentlyBeingLoaded =
new NamedThreadLocal<Set<EncodedResource>>("XML bean definition resources currently being loaded"){
@Override
protected Set<EncodedResource> initialValue() {
return new HashSet<>(4);
}
};
/**
* Load bean definitions from the specified XML file.
* @param encodedResource the resource descriptor for the XML file,
* allowing to specify an encoding to use for parsing the file
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of loading or parsing errors
*/
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 实际上从指定的 XML 文件加载 Bean 定义
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
//实际上从指定的 XML 文件加载 Bean 定义
/**
* Actually load bean definitions from the specified XML file.
* @param inputSource the SAX InputSource to read from
* @param resource the resource descriptor for the XML file
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of loading or parsing errors
* @see #doLoadDocument
* @see #registerBeanDefinitions
*/
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource);
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
}
在Spring中,配置类和注解都可以被转换为Bean定义(BeanDefinition)。下面是关于如何将配置类和注解转换为Bean定义的简要源码分析:
总而言之,无论是配置类还是注解,Spring都会通过解析注解并生成对应的Bean定义,最终将这些Bean定义注册到
DefaultListableBeanFactory中。这样,在容器启动时,Spring就能够根据这些Bean定义来实例化Bean并进行依赖注入。
配置类、注解转换为Spring BeanDefition源码后续博客中展示,敬请期待。
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
'}';
}
}
//通过BeanDefinitionBuilder构建
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
//通过属性设置
beanDefinitionBuilder.addPropertyValue("id", 1L)
.addPropertyValue("name","公众号:种棵代码技术树");
//获取BeanDefinition实例
BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
// BeanDefinition 并非 Bean 终态,可以自定义修改
System.out.println(beanDefinition);
// 2. 通过 AbstractBeanDefinition 以及派生类
GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
//设置Bean类型
genericBeanDefinition.setBeanClass(User.class);
//通过 MutablePropertyValues 批量操作属性
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("id",1L)
.add("name","公众号:种棵代码技术树");
// 通过 set MutablePropertyValues 批量操作属性
genericBeanDefinition.setPropertyValues(propertyValues);
作者:FirstMrRight
链接:
https://juejin.cn/post/7320779681673134091