BeanDefinitionRegistryPostProcessor接口有两个方法postProcessBeanFactory、postProcessBeanDefinitionRegistry,在spring容器初始化时执行,如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.edu.spring</groupId> <artifactId>spring</artifactId> <version>1.0.0</version> <name>spring</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> </dependencies> </project>
Persion.java
package com.edu.spring; public class Persion { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Persion [name=" + name + "]"; } }
MyBeanDefinitionRegistryPostProcessor.java
package com.edu.spring; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.stereotype.Component; @Component public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException { // TODO Auto-generated method stub } @Override public void postProcessBeanDefinitionRegistry( BeanDefinitionRegistry registry) throws BeansException { // TODO Auto-generated method stub for(int i=0;i<=10;i++){ BeanDefinitionBuilder bdb=BeanDefinitionBuilder.rootBeanDefinition(Persion.class); bdb.addPropertyValue("name","admin"+i); registry.registerBeanDefinition("persion"+i, bdb.getBeanDefinition()); } } }
App.java
package com.edu.spring; import java.util.Collection; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("com.edu.spring"); Collection<Persion> collection= context.getBeansOfType(Persion.class).values(); for(Persion p:collection){ System.out.println(p); } context.close(); } }
运行结果如下:
创建了11个bean,bean的名字为persion0... ..persion10,bdb.addPropertyValue("name","admin"+i);//给每个bean中的name属性设置值