1、定义基础仓库

package com.spring.generic.di;

public class BaseRepository<T> {

}

2、定义基础服务层

Spring泛型依赖注入
package com.spring.generic.di;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T> {

    @Autowired
    protected BaseRepository<T> repository;
    
    public void add(){
        System.out.println("add...");
        System.out.println(repository);
    }
}
Spring泛型依赖注入

3、定义User服务层

Spring泛型依赖注入
package com.spring.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{
    
}
Spring泛型依赖注入

4、定义仓库服务层

Spring泛型依赖注入
package com.spring.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{
    
}
Spring泛型依赖注入

5、测试类

Spring泛型依赖注入
package com.spring.generic.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-generic.xml");
        
        UserService userService = (UserService)ctx.getBean("userService");
        userService.add();
    }
}
Spring泛型依赖注入

相关文章:

  • 2021-06-19
  • 2021-12-24
  • 2022-02-15
  • 2021-08-07
  • 2021-10-14
  • 2022-12-23
  • 2022-02-05
  • 2021-09-12
猜你喜欢
  • 2021-07-03
  • 2021-12-21
  • 2021-04-04
  • 2021-07-24
  • 2022-12-23
相关资源
相似解决方案