编程语言
首页 > 编程语言> > java – 在Spring 4中导入Groovy Bean定义?

java – 在Spring 4中导入Groovy Bean定义?

作者:互联网

我已经使用groovy dsl定义了一些bean,并试图像我之前在dispatcher-servlet.xml中使用bean的xml定义一样添加它们:

<import resource="/WEB-INF/config.groovy"/>

但这不起作用.怎么了?

我的bean定义如下:

import org.apache.commons.dbcp.BasicDataSource

beans {
   dataSource(BasicDataSource) {
      driverClassName = "com.mysql.jdbc.Driver"
      url = "jdbc:mysql://localhost:3306/test"
      username = "root"
      password = "root"
   }
}

解决方法:

通过定义我自己的BeanPostprocessor来解决它:

public class GroovyConfigImporter implements BeanDefinitionRegistryPostProcessor {
    private static final Logger log = LoggerFactory.getLogger(GroovyConfigImporter.class);

    private final String config;

    public GroovyConfigImporter(String config) {
        this.config = config;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        log.info("Loading Groovy config '{}'", config);

        GroovyBeanDefinitionReader reader = new GroovyBeanDefinitionReader(registry);
        try {
            reader.importBeans(config);
        } catch (IOException e) {
            throw new ApplicationContextException("Can't open Groovy config '" + config + "'");
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }
}

然后在XML中定义:

<bean class="my.package.GroovyConfigImporter">
    <constructor-arg value="myConfig.groovy"/>
</bean>

标签:java,spring,groovy,spring-4
来源: https://codeday.me/bug/20190629/1322457.html