SpringBoot-Websphere-Java Config-web.xml-resource-ref

时间:2018-08-20 04:56:40

标签: spring-boot websphere

我有一个Web应用程序,其中在web.xml中定义了3个jndi资源 1个用于数据库,2个用于dyna缓存

如何在Spring Boot中将其转换为Java配置。

以下是应用程序中的示例资源引用配置

<resource-ref>
    <description>Resource reference for database</description>
    <res-ref-name>jdbc/dbname</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

<resource-ref id="cache1">
    <description>cache1 description</description>
    <res-ref-name>cache/cache1</res-ref-name>
    <res-type>com.ibm.websphere.cache.DistributedMap</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

<resource-ref id="cache2">
    <description>cache2 description</description>
    <res-ref-name>cache/cache2</res-ref-name>
    <res-type>com.ibm.websphere.cache.DistributedMap</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

谢谢

1 个答案:

答案 0 :(得分:-1)

@Configuration
@EnableTransactionManagement
@ComponentScan("org.example")
@EnableJpaRepositories(basePackages = "org.yours.persistence.dao")
public class PersistenceJNDIConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
      throws NamingException {
        LocalContainerEntityManagerFactoryBean em 
          = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());

        // rest of entity manager configuration
        return em;
    }

    @Bean
    public DataSource dataSource() throws NamingException {
        return (DataSource) new JndiTemplate().lookup("jdbc/dbname");
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    // rest of persistence configuration
}

我们将使用带有@Entity批注的简单模型,该批注具有生成的ID和名称:

@Entity
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    // default getters and setters
}

让我们定义一个简单的存储库:

@Repository
public class FooDao {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Foo> findAll() {
        return entityManager
          .createQuery("from " + Foo.class.getName()).getResultList();
    }
}

最后,让我们创建一个简单的服务:

@Service
@Transactional
public class FooService {

    @Autowired
    private FooDao dao;

    public List<Foo> findAll() {
        return dao.findAll();
    }
}

有了这个,您就拥有了在Spring应用程序中使用JNDI数据源所需的一切。