如何使用注释为spring设置context.xml?

时间:2015-04-16 20:38:07

标签: java xml spring tomcat

我正在使用Tomcat来托管webapp,并且想知道我是否可以使用Spring注释在tomcat的conf文件夹中创建等效的context.xml。示例context.xml

<?xml version="1.0" encoding="UTF-8"?> <!-- The contents of this file will be loaded for each web application -->
<Context> <!-- Default set of monitored resources -->
    <ResourceLink name="jdbc/SomeDB" global="jdbc/SomeDB" type="javax.sql.DataSource"/>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

如果可以使用注释,您可以通过示例向我展示它是如何完成的吗?

2 个答案:

答案 0 :(得分:0)

据我所知,没有与以下applicationContext.xml片段相同的注释:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">

    <jee:jndi-lookup
        id="someDbDataSource"
        jndi-name="jdbc/SomeDB"
        resource-ref="true" />
    ...

因为将数据源注入DAO非常容易:

public class SomeDbJdbcDaoSupport {

    public static final String SOME_DB_DATA_SOURCE = "someDbDataSource";
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier(SOME_DB_DATA_SOURCE)
    public void setSomeDbDataSource(DataSource dataSource) {
        if (jdbcTemplate == null || dataSource != jdbcTemplate.getDataSource()) {
            jdbcTemplate = new JdbcTemplate(dataSource);
        }
    }
    ...

数据源配置写入服务器配置文件,因为服务器管理连接池,但如果您使用其他池管理器(如c3po),则可以在spring configuration files中定义数据源属性,从而避免使用任何数据源服务器配置。

答案 1 :(得分:0)

我需要使用@ContextConfiguration指向我想要使用的xml。