EJB可以說原來執政黨Sun在platform選區大力支持的候選人,但含著金湯匙的EJB太過顢頇,給在野黨Spring有機可乘,成為Java playform的當選人。隨著支持度水漲船高,Spring3也逐漸肥起來,但還稱不上顢頇,面對Google出品的Guice謹慎以對,連Guice特有的annotation DI到Spring3也學得十足十。但Google挾著Android和GAE的優勢,端看Spring怎麼瘦身擠進Mobile和Cloud的大窄門。

  廢話結束,Spring3的@Import上還真的不太好用。寫一個DBConfig的@Configuration,提供DataSource的@Bean方便給application.xml與AnnotationConfigApplicationContext繼承,如下:

@Configuration
@ImportResource("classpath:resources.xml")
public class DBConfig {
    private static Logger logger = LoggerFactory.getLogger(DBConfig.class);
    private @Value("#{jdbcProperties.driverClassName}") String driverClass;
    private @Value("#{jdbcProperties.url}") String jdbcUrl;
    private @Value("#{jdbcProperties.username}") String username;
    private @Value("#{jdbcProperties.password}") String password;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(this.driverClass);
        dataSource.setUrl(this.jdbcUrl);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        logger.debug("init dataSource");
        return dataSource;
    }
}

  @Import不好用便在於@ImportResource只能引入XML,所以要寫一個resources.xml來放jdbc.properties的設定值。可是官方文件舉的飯粒竟然在Jetty不work,如下:

<beans>
<context:property-placeholder location="classpath:jdbc.properties"/>
</beans>

  那怎麼辦,結果參考之前component scan的飯粒,將resources.xml改寫如下,就OK了:

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">   
    <util:properties id="jdbcProperties" location="classpath:jdbc.properties"/>
</beans>

  很煩對吧!還要注意XML schema是否引入了spring-util-3.0.xsd,才能用<util:properties>。所以有需要連DB的Component類別,只需如下作法:

@Configuration
@Import(DBConfig.class)
public class AppConfig {
    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);
    @Bean
    public IBar ibar() {
        logger.debug("call Bar");
        return new BarImpl();
    }
}

  明明是用@Configuration,我卻稱為Component類別,當然也可以稱為AppConfig。但像@Configuration、@Component、@Service和@Repository等,等同於是一個Context的配置(不等於Context),@Import則是用annotation做到Spring 2.5時context可以繼承的功能。

  這時有個地方要特別小心,Bean只能被定義一處。我在BarImpl類別上加個@Repository,結果出現bean不是unique的Exception,也就是我在@Bean回傳BarImpl,等於是配置BarImpl是為一個Spring bean,而在BarImpl類別上加@Repository又宣告它一次是spring bean,導致出現non-unique的Exception

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()