【问题标题】:Hibernate + Spring MVC: external objects libraryHibernate + Spring MVC:外部对象库
【发布时间】:2012-02-01 06:41:30
【问题描述】:

我有两个使用相同数据库对象的不同应用程序(站点 + 一些 cron 实用程序)。我将它们移动到单独的库中,并且在应用程序中我只留下了 hibernate.configuration 文件。

现在,问题是我有一些使用 JavaMailSender 的电子邮件通知服务,它在 spring 配置文件中定义了属性:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="mail.xxx.com" />
        <property name="username" value="xxx" />
        <property name="password" value="xxx" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.ssl.trust">*</prop>
            </props>
        </property>
    </bean>
    <bean id="notificationsService" class="de.crm.NotificationsService">
        <property name="sender" ref="mailSender" />
        <property name="properties" ref="notificationsServiceProperties" />
    </bean>
    <bean id="notificationsServiceProperties" class="de.crm.objects.properties.NotificationsServiceProperties">
        <property name="name" value="xxx" />
        <property name="email" value="xxx" />
    </bean>

所以这里的主要问题是它看不到 de.crm.objects.properties.NotificationsServiceProperties 类,因为它是在外部库中定义的并且项目在导出时失败。

有没有办法将属性类留在外部库中并修复它? 谢谢

UPD#1:是否可以使用带有 @Autowired 注释的外部库 Spring 中的对象?

【问题讨论】:

  • 是外部jar添加到构建路径还是外部jar放在classpath中,从哪里可以读取?
  • 我已在 Buildpath 设置中将外部 jar 添加为外部库

标签: java hibernate spring-mvc


【解决方案1】:
So the main problem here that it can't see de.crm.objects.properties.NotificationsServiceProperties class because

它是在外部库中定义的,项目在导出时失败。

如果项目的类路径中未包含类/库,Spring 将无法识别它。所以你需要确保你的库无论是内部的还是外部的,都包含在类路径中。

UPD#1: Is it possible to use objects from external library Spring's with @Autowired annotation?

@Autowired 只提供那些存在于 spring 上下文中的对象。如果一个类在 spring 上下文之外,即使它包含在 classpath 中,@Autowired 也不会识别它。

编辑

首先,将类(例如,foo.Bar)添加到您的类路径中。

其次,在你的spring配置xml中添加一个新的bean定义:

<bean class="foo.Bar"></bean>

现在,您可以使用@Autowired 访问此对象:

public class SomeOtherClassInSpringContext {
    @Autowired
    Bar myBar;
}

附:如果你还没有这样做,你还需要应用&lt;context:annotation-config/&gt;&lt;context:component-scan base-package="path.to.your.classes"/&gt; 来告诉spring你已经为你的一些类配置了注解。

更多信息,请参考Spring docs

【讨论】:

  • 那么有什么办法可以将外部对象添加到 Spring 上下文中?
  • 啊,好吧,我已经做到了:)我解决了这个问题。您需要做的就是将外部 jar 添加到 WEB-INF/lib/ 目录。而且您不必在项目设置中将此 jar 添加为外部库。谢谢
【解决方案2】:

如果我没看错,您应该将包含外部类的 JAR 放在应用程序的类路径中。然后你的类将在 Spring 的上下文中可见。 例如,我们所做的就是配置数据源。 一般来说,Spring 可以处理类路径上的每个类...

【讨论】:

  • 什么意思?将此 jar 添加为外部库?我已经这样做了,没有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2019-04-01
  • 2014-08-05
相关资源
最近更新 更多