1. 程式人生 > >Sprinig泛型依賴註入

Sprinig泛型依賴註入

acf ctx -1 closed com lose pub pac ext

在父類中建立關系 (spring4.x以上版本)

技術分享
package com.spring.annotation.generic;

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

public class BaseService<T> {

    @Autowired
    private BaseRepository<T> dao;
    
    public void add(T entity){
        System.out.println("add by " + dao);
        dao.save(entity);
    }
    
}



package com.spring.annotation.generic; public class BaseRepository<T> { public void save(T entity){ System.out.println("save:" + entity); } }
View Code

子類

技術分享
package com.spring.annotation.generic;

import org.springframework.stereotype.Service;

@Service
public class UserService extends
BaseService<User>{ } package com.spring.annotation.generic; import org.springframework.stereotype.Repository; @Repository public class UserDao extends BaseRepository<User>{ }
View Code

測試

技術分享
package com.spring.annotation.generic;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml"); UserService userService = (UserService) ctx.getBean("userService"); userService.add(new User()); } }
View Code

結果

技術分享

Sprinig泛型依賴註入