spring之泛型依賴注入


目錄結構:

BaseRepository.java

package com.gong.spring.beans.generic.di;

public class BaseRepository<T> {

}

BaseService.java

package com.gong.spring.beans.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);
    }
}

User.java

package com.gong.spring.beans.generic.di;

public class User {

}

UserRepository.java

package com.gong.spring.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}

UserService.java

package com.gong.spring.beans.generic.di;

import org.springframework.stereotype.Service;

@Service(value="userService")
public class UserService extends BaseService<User>{
    
}

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.gong.spring.beans.generic.di"></context:component-scan>
</beans>

Main.java

package com.gong.spring.beans.generic.di;

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


public class Main {
    public static void main(String[] args) {
        //1.創建spring的IOC容器對象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic.di.xml");
        //2.從容器中獲取Bean實例
        UserService userService = (UserService) ctx.getBean("userService");
        userService.add();
        
    }
}

輸出:

說明:所謂泛型依賴注入,就是在父類建立了引用關系,子類繼承父類也會建立這種引用關系,並且真正注入的是T對應的子類類型。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM