Страницы

Поиск по вопросам

четверг, 9 апреля 2020 г.

Сквозное логирование при помощи Spring java

#java #spring #aop

                    
Пишу небольшой проектик, будет в итоге типа социальной сети. Сейчас самое начало работы. 

Есть класс Contact, содержащий информацию о человеке. Интерфейс ContactDAO, для работы
с базой данных и тестовая его реализация с мапой ContactSimpleDAO. Сервисная прослойка
интерфейс ContactServise и его реализация ContactManager. 

Весь проект есть на Github 
Попыталась допилить логгер. Проставила аннотацию @AutoLogging над классами, методы
которых нужно логировать и написала соответствующий BeanPostProcessor:

public class AutoLoggingBeanPostProcessor implements BeanPostProcessor {

    Map classMap = new HashMap<>();
    private AutoLoggingController loggingController = new AutoLoggingController();
    final Logger logger = LoggerFactory.getLogger(AutoLogging.class);

    public AutoLoggingBeanPostProcessor() throws Exception {
        MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
        platformMBeanServer.registerMBean(loggingController, new ObjectName("autologging",
"name", "autologger"));
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws
BeansException {
        Class beanClass = bean.getClass();
        if (beanClass.isAnnotationPresent(AutoLogging.class)) {
            classMap.put(beanName, beanClass);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws
BeansException {
        Class beanClass = classMap.get(beanName);
        if (beanClass != null) {
            return Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(),
new InvocationHandler() {

                @Override
                public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
                    if (loggingController.isEnabled()) {
                        logger.debug("Call method " + method + " with args: " + Arrays.toString(args));
                        Object result;
                        try {
                            result = method.invoke(bean, args);
                            logger.debug("Method " + method + " returns " + result);
                            return result;
                        } catch (Exception e) {
                            logger.error("Method " + method + "threw Exception ", e);
                            throw e;
                        }
                    } else {
                        return method.invoke(bean, args);
                    }
                }
            });
        }
        return bean;
    }
}


Спринговые конфигурации:

@Configuration
@PropertySource("classpath:ContactBookMaximumSize.properties")
@PropertySource("classpath:contacts.properties")
@ComponentScan(basePackages = {"com.stoxa.springjavaconfig.*"},
    nameGenerator = KsushikBeanNameGenerator.class)
public class AppConfig {
    @Bean
    public ContactBeanFactory contactBeanFactory() {
        return new ContactBeanFactory();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer configurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }

    @Value("${maxSize}")
    private int maxContactBookSize;

    @Bean
    public ContactDAO dao() throws Exception {
        final ContactSimpleDAO dao = new ContactSimpleDAO();
        Map contacts = new HashMap();
        contacts.put(contactBeanFactory().getObject().getPhone(),contactBeanFactory().getObject());
        contacts.put(contactBeanFactory().getObject().getPhone(),contactBeanFactory().getObject());
        contacts.put(contactBeanFactory().getObject().getPhone(),contactBeanFactory().getObject());
        contacts.put(contactBeanFactory().getObject().getPhone(),contactBeanFactory().getObject());
        contacts.put(contactBeanFactory().getObject().getPhone(),contactBeanFactory().getObject());
        dao.setContacts(contacts);
        return dao;
    }

    @Bean(initMethod = "init")
    public ContactService contactService() throws Exception {
        ContactManager contactService = new ContactManager();
        contactService.setDao(dao());
        contactService.setMaxContactBookSize(maxContactBookSize);
        return contactService;
    }

    @Bean
    public ApplicationEventPublisherAware applicationEventPublisherAware() {
        return new ContactManager();
    }

    @Bean
    ApplicationListener applicationListener() {
        return new DeleteContactListener();
    }

    @Bean
    public AutoLoggingBeanPostProcessor autologgingBeanPostProcessor() throws Exception {
        return new AutoLoggingBeanPostProcessor();
    }
}




При попытке скомпилить получаю ошибку:

Dec 14, 2015 11:40:09 PM org.springframework.context.annotation.AnnotationConfigApplicationContext
prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@37a71e93:
startup date [Mon Dec 14 23:40:09 EET 2015]; root of context hierarchy
Dec 14, 2015 11:40:09 PM org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker
postProcessAfterInitialization
INFO: Bean 'appConfig' of type [class com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6]
is not eligible for getting processed by all BeanPostProcessors (for example: not eligible
for auto-proxying)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Dec 14, 2015 11:40:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext
refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'contactService' defined in com.stoxa.springjavaconfig.Config.AppConfig: Bean
instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.Service.ContactService]: Factory
method 'contactService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:84)
    at com.stoxa.springjavaconfig.TestClass.TestClass.main(TestClass.java:23)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.stoxa.springjavaconfig.Service.ContactService]: Factory method 'contactService'
threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 13 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig: Bean instantiation
via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.dao()
    at com.stoxa.springjavaconfig.Config.AppConfig.contactService(AppConfig.java:69)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.CGLIB$contactService$0()
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6$$FastClassBySpringCGLIB$$dd5529ed.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.contactService()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 14 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao' threw exception;
nested exception is java.lang.IllegalArgumentException: Cannot subclass final class
class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 35 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class
com.sun.proxy.$Proxy14
    at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
    at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.enhanceFactoryBean(ConfigurationClassEnhancer.java:402)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:301)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.contactBeanFactory()
    at com.stoxa.springjavaconfig.Config.AppConfig.dao(AppConfig.java:57)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.CGLIB$dao$5()
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6$$FastClassBySpringCGLIB$$dd5529ed.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.dao()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 36 more

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'contactService' defined in com.stoxa.springjavaconfig.Config.AppConfig:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.Service.ContactService]: Factory
method 'contactService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:84)
    at com.stoxa.springjavaconfig.TestClass.TestClass.main(TestClass.java:23)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.stoxa.springjavaconfig.Service.ContactService]: Factory method 'contactService'
threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 13 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'dao' defined in com.stoxa.springjavaconfig.Config.AppConfig: Bean instantiation
via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao'
threw exception; nested exception is java.lang.IllegalArgumentException: Cannot subclass
final class class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.dao()
    at com.stoxa.springjavaconfig.Config.AppConfig.contactService(AppConfig.java:69)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.CGLIB$contactService$0()
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6$$FastClassBySpringCGLIB$$dd5529ed.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.contactService()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 14 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.stoxa.springjavaconfig.DAO.ContactDAO]: Factory method 'dao' threw exception;
nested exception is java.lang.IllegalArgumentException: Cannot subclass final class
class com.sun.proxy.$Proxy14
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 35 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class
com.sun.proxy.$Proxy14
    at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
    at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.enhanceFactoryBean(ConfigurationClassEnhancer.java:402)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:301)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.contactBeanFactory()
    at com.stoxa.springjavaconfig.Config.AppConfig.dao(AppConfig.java:57)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.CGLIB$dao$5()
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6$$FastClassBySpringCGLIB$$dd5529ed.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
    at com.stoxa.springjavaconfig.Config.AppConfig$$EnhancerBySpringCGLIB$$ade870a6.dao()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 36 more


Пожалуйста, помогите разобраться.
    


Ответы

Ответ 1



В общем, ваша проблема в том, что вы вызываете метод contactBeanFactory внутри @Bean-метода dao(). Или в том, что вы подменяете ContactBeanFactory на прокси в своем AutoLoggingBeanPostProcessor, на выбор. Уберите аннотацию с ContactBeanFactory и вылетать перестанет. Как сделать сквозное логирование в FactoryBean'е с вашей конфигурацией - не знаю, я эту маску на стройке нашел. Судя по SPR-6602, когда делали @Configuration, столкнулись с тем, что getSomethingFactoryBean().getObject() возвращает каждый раз разные объекты, что не совпадало с поведением xml-конфигурации. Поэтому придумали при вызове @Bean-метода, возвращающего FactoryBean проксировать результат, чтобы его getObject() возвращал кэшированый бин. Поскольку вы уже создали прокси, который является final-подклассом, сделать еще один подкласс нельзя, и все падает.

Ответ 2



Обратите внимание на вашу конфигурацию: при создании бина ContactDAO, вам требуется бин ContactBeanFactory. Вы пытаетесь получить его, вызвав метод contactBeanFactory(). В данном случае, при вызове метода contactBeanFactory(), вы не получите проинициализированный бин из контекста спринга, а будете получать новый объект на каждый вызов метода. Вероятно, следующие поправки в конфигурации решат вашу проблему: @Bean public ContactDAO dao(ContactBeanFactory contactBeanfactory) throws Exception { final ContactSimpleDAO dao = new ContactSimpleDAO(); Map contacts = new HashMap(); contacts.put(contactBeanFactory.getObject().getPhone(),contactBeanFactory.getObject()); contacts.put(contactBeanFactory.getObject().getPhone(),contactBeanFactory.getObject()); contacts.put(contactBeanFactory.getObject().getPhone(),contactBeanFactory.getObject()); contacts.put(contactBeanFactory.getObject().getPhone(),contactBeanFactory.getObject()); contacts.put(contactBeanFactory.getObject().getPhone(),contactBeanFactory.getObject()); dao.setContacts(contacts); return dao; } @Bean(initMethod = "init") public ContactService contactService(ContactDAO contactDAO) throws Exception { ContactManager contactService = new ContactManager(); contactService.setDao(contactDAO); contactService.setMaxContactBookSize(maxContactBookSize); return contactService; }

Комментариев нет:

Отправить комментарий