在xml引入帶有@Configuration的Java類,就是把這個帶有@Configuration的Java類,當做一個普通的的類用<bean>標簽引入:
核心代碼如下:
@Configuration public class AppConfig { @Autowired private DataSource dataSource; @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource); } @Bean public TransferService transferService() { return new TransferService(accountRepository()); } }
<beans> <!-- enable processing of annotations such as @Autowired and @Configuration -->
<!--這個必須要帶否則會報錯--> <context:annotation-config/> <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
<!--引入帶有@Configuration的Java類--> <bean class="com.acme.AppConfig"/> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>