08 spring中完成泛型依赖

2021-01-05  本文已影响0人  张力的程序园

接下来我们看一下如何在spring中完成泛型依赖。

1、前提约束

2、操作步骤

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;
    }
}
public class BaseRepository<T> {
}
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}
import javax.annotation.Resource;

public class BaseService<T> {

    @Resource
    protected BaseRepository<T> repository;

    public void add(){
        System.out.println("add...");
    }
}
import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{

}
import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{

}
<?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>
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中完成泛型依赖的过程。

上一篇 下一篇

猜你喜欢

热点阅读