jjzjj

Java Config @Bean 未在其他 @Configuration 类中 Autowiring

coder 2024-03-17 原文

尝试使用 Java Config 设置 Spring 4 Web 应用程序时,我遇到了将在配置类中创建的 bean Autowiring 到另一个配置类中的问题。 'dataSource' bean 在 MyBatisConfig 类中有一个空值。这似乎是配置中唯一未正确连接的 bean。查看 Spring 调试日志(请参阅下面最后一个代码块中日志的最后一部分)它看起来已正确实例化,但似乎也被破坏了?我的配置可能有什么问题?

PropertySourcesPlaceholderConfigurerConfig 类:

package nl.somesite.teamshot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class PropertySourcesPlaceholderConfigurerConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();

        propertyConfigurer.setLocation(new ClassPathResource("application.properties"));
        /*propertyConfigurer.setLocation(new ClassPathResource("file:${catalina.home}/conf/application.properties"));
        propertyConfigurer.setLocation(new ClassPathResource("/var/lib/openshift/517874b8e0b8cd218e000391/app-root/data/apache-tomcat-7.0.39/conf/application.properties"));*/

        propertyConfigurer.setIgnoreUnresolvablePlaceholders(false);
        propertyConfigurer.setIgnoreResourceNotFound(true);
        return propertyConfigurer;
    }

}

DbConfig 类:

package nl.somesite.teamshot.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({PropertySourcesPlaceholderConfigurerConfig.class})
public class DbConfig {

    private @Value("jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_MYSQL_DATABASE}") String url;
    private @Value("${OPENSHIFT_MYSQL_DB_USERNAME}") String username;
    private @Value("${OPENSHIFT_MYSQL_DB_PASSWORD}") String password;

    static Logger log = LogManager.getLogger(DbConfig.class.getName());

    @Bean
    public BasicDataSource dataSource() {
        log.debug("Creating dataSource bean, url =  "+ url);

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDefaultAutoCommit(false);

        log.debug("dataSource bean url = "+ dataSource.getUrl());
        return dataSource;
    }

}

MyBatisConfig 类:

package nl.somesite.teamshot.config;
import java.io.IOException;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@Import({DbConfig.class})
public class MyBatisConfig {

    @Autowired private BasicDataSource dataSource;


    static Logger log = LogManager.getLogger(MyBatisConfig.class.getName());

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() {
        log.debug("Creating SqlSessionFactoryBean, dataSource = " + dataSource);

        SqlSessionFactoryBean sqlSessionFactory =  new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        org.springframework.core.io.Resource[] classPathResources;
        try {
            classPathResources = resolver.getResources("classpath*:/mappers/*.xml");
            sqlSessionFactory.setMapperLocations(classPathResources);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return sqlSessionFactory;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        log.debug("Creating MapperScannerConfigurer");
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("nl.somesite.teamshot.data");
        return mapperScannerConfigurer;
    }

}

AppConfig 类:

package nl.somesite.teamshot.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"nl.somesite.teamshot.config"})
public class AppConfig {

}

AppInitializer 类:

package nl.somesite.teamshot.initializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class AppInitializer implements WebApplicationInitializer {

    private static final String CONFIG_LOCATION = "nl.somesite.teamshot.config";
    private static final String MAPPING_URL = "/";

    static Logger log = LogManager.getLogger(AppInitializer.class.getName());

    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        return context;
    }

}

WebMvcConfig 类:

package nl.somesite.teamshot.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {


    static Logger log = LogManager.getLogger(WebMvcConfig.class.getName());

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public ViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver =  new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

日志的最后一部分:

[DEBUG:] 2014-07-09 01:25:20 [DefaultSingletonBeanRegistry line:220] Creating shared instance of singleton bean 'dataSource'  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:449] Creating instance of bean 'dataSource'  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractBeanFactory line:249] Returning cached instance of singleton bean 'dbConfig'  
    [DEBUG:] 2014-07-09 01:25:20 [DbConfig line:25] Creating dataSource bean, url =  jdbc:mysql://localhost:3306/teamshot?useUnicode=true&characterEncoding=UTF-8  
    [DEBUG:] 2014-07-09 01:25:20 [DbConfig line:34] dataSource bean url = jdbc:mysql://localhost:3306/teamshot?useUnicode=true&characterEncoding=UTF-8  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:523] Eagerly caching bean 'dataSource' to allow for resolving potential circular references  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:477] Finished creating instance of bean 'dataSource'  
    [DEBUG:] 2014-07-09 01:25:20 [DefaultSingletonBeanRegistry line:220] Creating shared instance of singleton bean 'sqlSessionFactory'  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:449] Creating instance of bean 'sqlSessionFactory'  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractBeanFactory line:249] Returning cached instance of singleton bean 'myBatisConfig'  
    [DEBUG:] 2014-07-09 01:25:20 [MyBatisConfig line:27] Creating SqlSessionFactoryBean, dataSource = null  
    [DEBUG:] 2014-07-09 01:25:20 [PathMatchingResourcePatternResolver line:553] Looking for matching resources in directory tree [D:\Eclipse workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\teamshot\WEB-INF\classes\mappers]  
    [DEBUG:] 2014-07-09 01:25:20 [PathMatchingResourcePatternResolver line:615] Searching directory [D:\Eclipse workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\teamshot\WEB-INF\classes\mappers] for files matching pattern [D:/Eclipse workspaces/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/teamshot/WEB-INF/classes/mappers/*.xml]  
    [DEBUG:] 2014-07-09 01:25:20 [PathMatchingResourcePatternResolver line:354] Resolved location pattern [classpath*:/mappers/*.xml] to resources [file [D:\Eclipse workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\teamshot\WEB-INF\classes\mappers\newsitems.xml], file [D:\Eclipse workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\teamshot\WEB-INF\classes\mappers\teams.xml]]  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:523] Eagerly caching bean 'sqlSessionFactory' to allow for resolving potential circular references  
    [DEBUG:] 2014-07-09 01:25:20 [AbstractAutowireCapableBeanFactory line:1595] Invoking afterPropertiesSet() on bean with name 'sqlSessionFactory'  
    [DEBUG:] 2014-07-09 01:25:20 [DefaultSingletonBeanRegistry line:474] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3278a91: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,appConfig,dbConfig,myBatisConfig,propertySourcesPlaceholderConfigurerConfig,webMvcConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,dataSource,sqlSessionFactory,mapperScannerConfigurer,propertyConfigurer,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcConversionService,mvcValidator,mvcUriComponentsContributor,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,internalResourceViewResolver,newsItemMapper,teamMapper]; root of factory hierarchy  
    [DEBUG:] 2014-07-09 01:25:20 [DisposableBeanAdapter line:322] Invoking destroy method 'close' on bean with name 'dataSource'  
    [DEBUG:] 2014-07-09 01:25:20 [DisposableBeanAdapter line:244] Invoking destroy() on bean with name 'webMvcConfig'  
    [DEBUG:] 2014-07-09 01:25:20 [DisposableBeanAdapter line:244] Invoking destroy() on bean with name 'dbConfig'  
    [DEBUG:] 2014-07-09 01:25:21 [DisposableBeanAdapter line:244] Invoking destroy() on bean with name 'appConfig'  
    [DEBUG:] 2014-07-09 01:25:21 [DisposableBeanAdapter line:244] Invoking destroy() on bean with name 'propertySourcesPlaceholderConfigurerConfig'  
    [ERROR:] 2014-07-09 01:25:21 [ContextLoader line:331] Context initialization failed Error creating bean with name 'sqlSessionFactory' defined in class path resource [nl/somesite/teamshot/config/MyBatisConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required 
    jul 09, 2014 1:25:21 AM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [nl/somesite/teamshot/config/MyBatisConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:681)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)
    Caused by: java.lang.IllegalArgumentException: Property 'dataSource' is required
        at org.springframework.util.Assert.notNull(Assert.java:112)
        at org.mybatis.spring.SqlSessionFactoryBean.afterPropertiesSet(SqlSessionFactoryBean.java:337)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
        ... 22 more

如果我禁用 Spring 调试日志记录,我会看到:

[DEBUG:] 2014-07-09 11:02:19 [MyBatisConfig line:50] Creating MapperScannerConfigurer  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [DbConfig line:24] Creating dataSource bean, url =  jdbc:mysql://localhost:3306/teamshot?useUnicode=true&characterEncoding=UTF-8  
[DEBUG:] 2014-07-09 11:02:20 [DbConfig line:33] dataSource bean url = jdbc:mysql://localhost:3306/teamshot?useUnicode=true&characterEncoding=UTF-8  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[DEBUG:] 2014-07-09 11:02:20 [MyBatisConfig line:30] Creating SqlSessionFactoryBean, dataSource = null  
[ERROR:] 2014-07-09 11:02:20 [ContextLoader line:331] Context initialization failed Error creating bean with name 'sqlSessionFactory' defined in class path resource [nl/somesite/teamshot/config/MyBatisConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required 

最佳答案

在阅读了很多与 Spring 相关的内容之后,我发现 MapperScannerConfigurer 是 BeanFactoryPostProcessor 的一个实现。在 @Configuration 类中使用 BeanFactoryPostProcessor 会破坏该 @Configuration 类的默认后处理。

There is a fundamental lifecycle conflict in handling BeanFactoryPostProcessor @Bean methods within @Configuration classes that use @Autowired, @PostConstruct, @Value, etc. Because BFPPs must be instantiated early in the lifecycle, they cause early instantiation of their declaring @Configuration class - too early to recieve the usual post-processing by AutowiredAnnotationBeanPostProcessor and friends. See https://jira.spring.io/browse/SPR-8269

将 MapperScannerConfigurer bean 方法从 MyBatisConfig 分离到它自己的类中解决了这个问题。

关于Java Config @Bean 未在其他 @Configuration 类中 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24643426/

有关Java Config @Bean 未在其他 @Configuration 类中 Autowiring的更多相关文章

  1. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  4. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  5. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  6. ruby - 如何将 Puma::Configuration 传递给 Sinatra? - 2

    这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp

  7. ruby-on-rails - 将 Rails 路由助手作为类方法添加到类中 - 2

    我如何将像“root_path”这样的Rails路由助手作为类方法添加到像my_model.rb这样的类中?所以我的课是这样的:ClassMyModeldefself.fooreturnself.root_pathendendMyModel.foo以上不起作用,因为ClassMyModel不响应root_path这是我所知道的:我可以使用includeRails.application.routes.url_helpers,但这只会将模块的方法添加为实例方法我试过扩展Rails.application.routes.url_helpers但它没用请随时给我上课:)

  8. ruby-on-rails - 在条件路由期间未在 Rails 3 中设置 request.subdomain - 2

    我正在尝试根据RyanBatesscreencastonsubdomains在Rails3中设置子域.但是它对我不起作用。我有以下设置:#routes.rbconstraints(Subdomain)doget'devices'=>'devices#all'end#lib/subdomain.rbclassSubdomaindefself.matches?(request)#binding.pryrequest.subdomain.present?&&request.subdomain=="admin"endend加载urladmin.localhost:3000/devices应该将

  9. ruby-on-rails - Ruby on Rails,在更新其他列值时更改列值 - 2

    我在Rails模型中有两列相互关联:Article.bodyArticle.body_updated_on每次Article.body更新时,我想将Article.body_updated_on更改为Time.now。如果任何其他字段已更新,则无需进行任何操作。 最佳答案 只需在将回调保存到您的文章模型之前添加classArticle 关于ruby-on-rails-RubyonRails,在更新其他列值时更改列值,我们在StackOverflow上找到一个类似的问题:

  10. ruby-on-rails - 用一系列时间增量填充选择,加上其他选项 - 2

    使用RubyonRails,我使用给定的增量(例如每30分钟)用时间填充“选择”。目前我正在YAML文件中写出所有的可能性,但我觉得有一种更巧妙的方法。我想我想提供一个开始时间、一个结束时间、一个增量,并且目前只提供一个名为“关闭”的选项(想想“business_hours”)。所以,我的选择可能会显示:'Closed'5:00am5:30am6:00am...[allthewayto]...11:30pm谁能想出更好的方法,或者只是将它们全部“拼写”出来的最佳方法? 最佳答案 此答案基于@emh的答案。defcreate_hour

随机推荐