import com.duxiu.modules.beetlsql.BeetlSQLDao;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.Objects;
import java.util.stream.Stream;
public class DaoFactoryBean implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(applicationContext);
SQLManager sqlManager = applicationContext.getBean(SQLManager.class);
try {
Resource[] resources = rpr.getResources("classpath:com/duxiu/**/*.class");
Stream.of(resources).map(f -> {
try {
return f.getURI().getPath().split("(classes/)|(!/)")[1].replace("/", ".").replace(".class", "");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}).filter(Objects::nonNull).forEach(f -> {
try {
Class<?> aClass = Class.forName(f);
boolean match = Stream.of(aClass.getAnnotations()).anyMatch(c -> c instanceof BeetlSQLDao);
if (match && !beanFactory.containsBean(aClass.getSimpleName())) {
System.out.println(sqlManager.getMapper(aClass));
//beanFactory.registerSingleton(aClass.getSimpleName(),sqlManager.getMapper(aClass));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(applicationContext.getBean(SQLManager.class));
/*if(!beanFactory.containsBean(beanName)){
BeanDefinitionBuilder beanDefinitionBuilder= BeanDefinitionBuilder.rootBeanDefinition(beanClass);
beanDefinitionBuilder.addPropertyValue("host", host);
beanDefinitionBuilder.addPropertyValue("port", port);
beanDefinitionBuilder.addPropertyValue("database", database);
beanDefinitionBuilder.setInitMethodName("init");
beanDefinitionBuilder.setDestroyMethodName("destroy");
beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
logger.info("Add {} to bean container.", beanName);
}*/
}
}
posted on 2016-03-23 10:47
SIMONE 阅读(1707)
评论(0) 编辑 收藏