我使用自定义BeanFactory进行了解析。如果有人提出更好的解决方案,我将很高兴听到。无论如何,这是bean工厂:
import java.util.Set;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.BeansException;import org.springframework.beans.TypeConverter;import org.springframework.beans.factory.config.DependencyDescriptor;import org.springframework.beans.factory.support.DefaultListableBeanFactory;public class CustomBeanFactory extends DefaultListableBeanFactory { public CustomBeanFactory() { } public CustomBeanFactory(DefaultListableBeanFactory delegate) { super(delegate); } @Override public Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { //Assign Logger parameters if required if (descriptor.isRequired() && Logger.class.isAssignableFrom(descriptor .getMethodParameter().getParameterType())) { return LoggerFactory.getLogger(descriptor.getMethodParameter() .getDeclaringClass()); } else { return super.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); } }}
XML配置的用法示例:
CustomBeanFactory customBeanFactory = new CustomBeanFactory(); GenericApplicationContext ctx = new GenericApplicationContext(customBeanFactory); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); xmlReader.loadBeanDefinitions(new ClassPathResource("beans.xml")); ctx.refresh();
编辑:
您可以在下面找到Arend v。Reinersdorffs的改进版本(请参阅注释以获取解释)。
import java.lang.reflect.Field;import java.util.Set;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.BeansException;import org.springframework.beans.TypeConverter;import org.springframework.beans.factory.config.DependencyDescriptor;import org.springframework.beans.factory.support.DefaultListableBeanFactory;import org.springframework.core.MethodParameter;public class CustomBeanFactory extends DefaultListableBeanFactory { public CustomBeanFactory() { } public CustomBeanFactory(DefaultListableBeanFactory delegate) { super(delegate); } @Override public Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { //Assign Logger parameters if required if (Logger.class == descriptor.getDependencyType()) { return LoggerFactory.getLogger(getDeclaringClass(descriptor)); } else { return super.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); } } private Class<?> getDeclaringClass(DependencyDescriptor descriptor) { MethodParameter methodParameter = descriptor.getMethodParameter(); if (methodParameter != null) { return methodParameter.getDeclaringClass(); } Field field = descriptor.getField(); if (field != null) { return field.getDeclaringClass(); } throw new AssertionError("Injection must be into a method parameter or field."); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)