import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
/**
* 类 名: MyAutoConfiguredMyBatisRegistrar
* 描 述: 测试动态注入Bean到Spring容器中
*/
public class MyAutoConfiguredMyBatisRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanFactoryAware {
private ResourceLoader resourceLoader;
/**
* 动态置顶扫描包路径下特殊的类加载到Bean中
* @param importingClassMetadata
* @param registry
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Class[] classes = {IOrderMapper.class,IVipMapper.class,IProductMapper.class};
for(Class c : classes){
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(c);
beanDefinition.setBeanClass(CustomFactoryBean.class);
System.out.println("-----------------c.getName()---------------------------"+c.getName());
registry.registerBeanDefinition(c.getName(), beanDefinition);
}
}
/**
* 获取Spring中的一些元数据
* @param resourceLoader
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
}
}
import com.fen.dou.factorybeanStu.annotation.TableName;
import com.fen.dou.factorybeanStu.utils.ConnectionUtils;
import com.fen.dou.factorybeanStu.vo.OrderVo;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* @author yangcai
* @version 1.1.6
* @Description TODO
* @createTime 2022年03月21日 14:23:00
*/
public class CustomFactoryBean implements FactoryBean , InvocationHandler, BeanNameAware {
@Override
public void setBeanName(String name) {
System.out.println("----------------------------实例化Name----------------------------"+name);
}
private Class aClass;
public CustomFactoryBean(Class c){
System.out.println("----------------------------实例化----------------------------"+c.getName());
this.aClass = c;
}
@Override
public Object getObject() {
System.out.println("----------------------------getObject----------------------------");
return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {aClass}, this);
}
@Override
public Class<?> getObjectType() {
return aClass;
}
Connection getConnection() {
try {
String url = "jdbc:mysql://localhost:3306/mycat?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
String mysqlusername ="root";
String password = "123456";
return DriverManager.getConnection(url, mysqlusername, password);
}catch (Exception e){
System.out.println("============创建连接失败============");
}
return null;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Connection connection = ConnectionUtils.getConnection();
String tableName = null;
Annotation[] annotation = aClass.getAnnotations() ;
for(Annotation anno : annotation){
if(anno.annotationType().equals(TableName.class)){
TableName tableNamaAnno = (TableName)anno;
tableName = tableNamaAnno.value();
}
}
List<OrderVo> list = new ArrayList<>();
if(method.getName().equals("queryById")){
System.out.println("---------jdbc查询数据库--------------");
PreparedStatement preparedStatement = connection.prepareStatement("select * from "+tableName+" where id = ?");
preparedStatement.setInt(1,Integer.valueOf(String.valueOf(args[0])));
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
OrderVo orderVo = new OrderVo();
Integer id = rs.getInt(1);
if(id != null){
orderVo.setId(id);
}
String name = rs.getString(2);
if(name != null){
orderVo.setName(name);
}
list.add(orderVo);
}
}
return list;
}
}
@TableName("order_info")
public interface IOrderMapper {
public List<OrderVo> queryById(Integer id);
}
@TableName("product_info")
public interface IProductMapper {
public void update();
}
@TableName("vip_info")
public interface IVipMapper {
public void update();
}
其中使用ImportBeanDefinitionRegistrar接口,去创建beanDefinition
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(c);
是给带参构造器传入参数的,如果添加一个参数则调动一个参数的构造器
public CustomFactoryBean(Class c){
System.out.println("----------------------------实例化----------------------------"+c.getName());
this.aClass = c;
}
如果添加两个构造器参数:
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(c);
beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("dsadsadasdasdsadsadsa");
则调用两个参数的构造器
public CustomFactoryBean(Class c,String name){
System.out.println("----------------------------实例化----------------------------"+c.getName());
this.aClass = c;
System.out.println("----------带参构造器-----------"+name);
}
则上述代码,创建了三个beanDefinition
?
?
在后续通过反射调用构造器实例化的时候,把beanDefinition变成bean,则singletonObjects单例池中会生成三个bean,并且类型都是CustomFactoryBean.class
com.fen.dou.factorybeanStu.IOrderMapper -->??CustomFactoryBean.class
com.fen.dou.factorybeanStu.IProductMapper-->??CustomFactoryBean.class
com.fen.dou.factorybeanStu.IVipMapper-->??CustomFactoryBean.class
?当我们执行
CustomFactoryBean orderMapper = (CustomFactoryBean)ac.getBean("&com.fen.dou.factorybeanStu.IOrderMapper");
会把&去掉,用com.fen.dou.factorybeanStu.IOrderMapper去获取实例bean
当我们执行:
IOrderMapper or = (IOrderMapper)ac.getBean("com.fen.dou.factorybeanStu.IOrderMapper");
也是用com.fen.dou.factorybeanStu.IOrderMapper去获取实例bean,然后调用bean的 getObject()方法去实例化bean,放入FactoryBean实例池中去
其实这两者的不同点就是通过?& 来判断的,具体可以去看源码
|