泛型依赖注入

Spring入门第十五课_spring

 

看代码:

package logan.spring.study.generic.di;

public class BaseRepository<T> {

}

 

package logan.spring.study.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);
    }
    
    
}
package logan.spring.study.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{
    

}
package logan.spring.study.generic.di;

public class User{

}
 
package logan.spring.study.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<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: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="logan.spring.study.generic.di"></context:component-scan>

</beans>
package logan.spring.study.generic.di;

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

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        userService.add();
        

    }

}

输出结果:

五月 27, 2017 2:04:02 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Sat May 27 14:04:02 CST 2017]; root of context hierarchy
五月 27, 2017 2:04:02 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-generic.xml]
add...
logan.spring.study.generic.di.UserRepository@43a0cee9

 

心再坚强也不要独自飞翔