gpt4 book ai didi

java - 带有 bean 的 Spring-Core JNDI 配置

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:59 24 4
gpt4 key购买 nike

假设我有一个类,如下所示:

public interface UserDAO {
public List<User> list();
}

public class UserDAOImpl implements UserDAO {
private DataSource dataSource;

public UserDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}

假设 JNDI 配置已在 tomcat 中正确完成。

现在在许多站点中,对于 spring bean 映射,我发现了以下配置:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/UsersDB"/>
</bean>

<bean id="userDao" class="net.codejava.spring.dao.UserDAOImpl">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean>

这是我的问题,UserDAOImpl 类正在寻找 DataSource 对象,但我们正在注入(inject) JndiObjectFactoryBean 对象[它不是 DataSource 的子类],因为我们甚至没有提到工厂方法如何或在哪里发生转换?

最佳答案

JndiObjectFactoryBeanorg.springframework.beans.factory.FactoryBean 类型的 bean。此 bean 用作要公开的对象的工厂。以下是 FactoryBean 的 javadoc 的摘录;

Interface to be implemented by objects used within a BeanFactory which are themselves factories for individual objects. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.

NB: A bean that implements this interface cannot be used as a normal bean. A FactoryBean is defined in a bean style, but the object exposed for bean references (getObject()) is always the object that it creates.

FactoryBeans can support singletons and prototypes, and can either create objects lazily on demand or eagerly on startup. The SmartFactoryBean interface allows for exposing more fine-grained behavioral metadata.

因此,当 spring 框架将数据源 Autowiring 到 useDaoImpl 时,它会检查 dataSource 是否是 FactoryBean 类型的 bean,在本例中就是这样,因此它将从 getObject() JndiObjectFactoryBean 方法到数据源。如果您想进一步了解这一点,请查看在本例中执行 Autowiring 的 ClassPathXmlApplicationContext.finishBeanfactoryInitialization(..)DefaultListableBeanFactory.preInstantiateSingletons() 方法。

关于java - 带有 bean 的 Spring-Core JNDI 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com