Spring 允許通過<import> 将多個配置檔案引入到一個檔案中,進行配置檔案的內建。這樣在啟動 Spring 容器時,僅需要指定這個合并好的配置檔案就可以。
import 元素的 resource屬性支援 Spring 的标準的路徑資源
Main
package com.spring.beans.generic.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans-generic-di.xml");
UserService ur = (UserService) ac.getBean("userService");
ur.add();
}
}
/*
add
[email protected]
*/
beans-generic-di.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.spring.beans.generic.di">
</context:component-scan>
</beans>
BaseService<T>
package com.spring.beans.generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseService<T> {
@Autowired
private BaseRepository<T> repository;
public void add() {
System.out.println("add");
System.out.println(repository);
}
}
UserService
package com.spring.beans.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
BaseRepository<T>
package com.spring.beans.generic.di;
public class BaseRepository<T> {
}
UserRepository
package com.spring.beans.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository<User>{
}
User
package com.spring.beans.generic.di;
public class User {
}