接下来我们看一下如何在spring中完成泛型依赖。
1、前提约束
- 创建一个spring项目 https://www.jianshu.com/p/881728c97c3c
2、操作步骤
- 在src/main/java中创建net.wanho.User.java,内容如下:
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中创建net.wanho.BaseRepository.java,内容如下:
public class BaseRepository<T> {
}
- 在src/main/java中创建net.wanho.UserRepository .java,内容如下:
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository<User>{
}
- 在src/main/java中创建net.wanho.BaseService.java,内容如下:
import javax.annotation.Resource;
public class BaseService<T> {
@Resource
protected BaseRepository<T> repository;
public void add(){
System.out.println("add...");
}
}
- 在src/main/java中创建net.wanho.UserService.java,内容如下:
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
- 在src/main/java中创建net.wanho.UserService.java,内容如下:
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
- 在src/main/resources中创建application.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: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中创建net.wanho.Test.java,内容如下:
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中完成泛型依赖的过程。
网友评论