接下來(lái)我們看一下如何在spring中完成泛型依賴秸弛。
1四康、前提約束
- 創(chuàng)建一個(gè)spring項(xiàng)目 http://www.reibang.com/p/881728c97c3c
2搪搏、操作步驟
- 在src/main/java中創(chuàng)建net.wanho.User.java,內(nèi)容如下:
import java.io.Serializable;
public class User implements Serializable {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 在src/main/java中創(chuàng)建net.wanho.BaseRepository.java闪金,內(nèi)容如下:
public class BaseRepository<T> {
}
- 在src/main/java中創(chuàng)建net.wanho.UserRepository .java疯溺,內(nèi)容如下:
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository<User>{
}
- 在src/main/java中創(chuàng)建net.wanho.BaseService.java论颅,內(nèi)容如下:
import javax.annotation.Resource;
public class BaseService<T> {
@Resource
protected BaseRepository<T> repository;
public void add(){
System.out.println("add...");
}
}
- 在src/main/java中創(chuàng)建net.wanho.UserService.java,內(nèi)容如下:
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
- 在src/main/java中創(chuàng)建net.wanho.UserService.java囱嫩,內(nèi)容如下:
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
- 在src/main/resources中創(chuàng)建application.xml恃疯,內(nèi)容如下:
<?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:mvc="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.xsd">
<mvc:component-scan base-package="net.wanho"></mvc:component-scan>
</beans>
- 在src/main/java中創(chuàng)建net.wanho.Test.java,內(nèi)容如下:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
UserService userService = (UserService) ctx.getBean("userService");
userService.add();
}
}
以上就是在spring中完成泛型依賴的過(guò)程墨闲。