【发布时间】:2012-12-07 16:23:57
【问题描述】:
我以编程方式设置了我的应用程序配置,并且我正在导入这样的 bean:
@Configuration
@ImportResource( value= { "classpath:myBean.xml"})
public class AppConfig extends WebMvcConfigurerAdapter
{
在myBean.xml 我有这个:
<bean id="myBeanId" class="my.domain.myBeanClass">
<property name="sessionFactory" ref="my_session_factory" />
<property name="someOtherProperty"...
</bean>
这工作正常,sessionFactory 被注入到myBeanClass。
但是,如果我尝试以编程方式实例化同一个 bean,将 ImportResource 转换为 Import,我会收到“没有为依赖项找到类型 [org.hibernate.SessionFactory] 的匹配 bean...”错误。
@Configuration
@Import(BeanConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter
{
Bean 配置类:
@Configuration
public class BeanConfig
{
@Autowired
private SessionFactory sessionFactory;
@Bean(name="myBeanId")
public MyBeanClass createMyBeanClass()
{
MyBeanClass mbc = new MyBeanClass();
mbc.setSessionFactory(sessionFactory);
....
return mbc;
编辑:肯定会创建 sessionFactory bean,如果我将 required = false 添加到 @Autowired,然后在加载所有内容后手动注入 sessionFactory。它工作正常。
编辑 2: 我没有 web.xml,我使用的是 servlet 3,所以以编程方式声明了所有内容。这是我的 web.xml 等价物
@Configuration
public class WalletInitialiser implements WebApplicationInitializer
{
@Override
public void onStartup(ServletContext aServletContext) throws ServletException
{
AnnotationConfigWebApplicationContext mvcContext
= new AnnotationConfigWebApplicationContext();
mvcContext.register(AppConfig.class);
mvcContext.scan("config.packages", "class.packages");
aServletContext.addListener(new ContextLoaderListener(mvcContext));
//add security filters, dispatcher to servlet, logback
我在另一个类中配置了我的 SessionFactory,配置包中的 HibernateConfig 正在从
中获取mvcContext.scan("config.packages", "class.packages");
该课程的摘录是:
@Configuration
@EnableTransactionManagement
public class HibernateConfig
{
@Bean(name="my_session_factory")
public LocalSessionFactoryBean baseSessionFactory()
{
LocalSessionFactoryBean lsfb= new LocalSessionFactoryBean();
lsfb.setPackagesToScan("class.packages");
lsfb.setAnnotatedPackages("class.packages");
//add hibernate props for datasource
return lsfb;
}
}
【问题讨论】:
-
你是否开启了基于注解的上下文配置(myBean.xml)??
-
能否请您展示您如何使用容器配置 AppConfig(此 AppConfig 的 web.xml 条目),您可能还有另一个配置,您可以在其中定义 SessionFactory 权限,能否请您展示该配置也
-
这很奇怪,您使用的是注释驱动的配置,但随后从 xml 文件中导入了一个 bean。您也可以删除基于 java 的注释的 conifg,因为它无论如何都依赖于 xml。这是不必要的混乱。
-
我给出的第一个示例,我使用 myBean.xml,只是因为注释驱动方式不起作用。我不打算把它留在里面。这只是一个例子,表明
@Import和@ImportResource对待事物的方式有所不同。
标签: java spring javabeans code-injection