why use JndiObjectFactoryBean to config JNDI datasource did not work?

前端 未结 2 1711
挽巷
挽巷 2020-12-29 15:24

when I uss Java-base to config my JNDI. Spring 4.2.5.

But If I use JndiObjectFactoryBean to config.when I want to get the datasource,the object will be

相关标签:
2条回答
  • 2020-12-29 15:50

    I landed here without realizing this was a problem I had faced in the past - Error Casting Spring's JndiObjectFactoryBean to ConnectionFactory for Solace-MQ JMS

    So a workaround (not the preferred way) is to call afterPropertiesSet() on jndiObjectFactoryBean before attempting to getObject()

    @Bean
        public DataSource dataSource(){
            JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
            jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
            jndiObjectFactoryBean.setResourceRef(true);
            jndiObjectFactoryBean.setProxyInterface(DataSource.class);
            jndiObjectFactoryBean.afterPropertiesSet();
            return (DataSource) jndiObjectFactoryBean.getObject();  //NOT NULL
        }
    
    0 讨论(0)
  • 2020-12-29 16:00

    The actual lookup in JndiObjectFactoryBean is done in the lifecycle callback method. Either call the method explictly in your @Bean method like this (workaround)

        @Bean
        public DataSource dataSource(){
            JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
            jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
            jndiObjectFactoryBean.setResourceRef(true);
            jndiObjectFactoryBean.setProxyInterface(DataSource.class);
            jndiObjectFactoryBean.afterPropertiesSet();
            return (DataSource) jndiObjectFactoryBean.getObject();  //NULL!!!
        }
    

    Or the better approach. Let your @Bean method return the JndiObjectFactoryBean and manage its lifecyle. Then in your dependent beans that require a DataSource inject the datasource created from the factory

        @Bean
        public JndiObjectFactoryBean dataSource(){
            JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
            jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
            jndiObjectFactoryBean.setResourceRef(true);
            jndiObjectFactoryBean.setProxyInterface(DataSource.class);
            return jndiObjectFactoryBean;
        }
    
    //in your dependnecy
    
    @Bean
    public SomeBean someBean(DataSource dataSource){
       //use the injected datasource shich comes from the factory
    }
    
    0 讨论(0)
提交回复
热议问题