目录

基础

Demo

结果


基础

Spring系列:IOC依赖查找(根据注解查找)实例

 

Demo

content-inject.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--实时查找-->
    <import resource="content.xml" />

    <bean id="userRepos" class="com.test.repos.UserRepos" autowire="byType" />

 </beans>

UserRepos 

package com.test.repos;

import com.test.pojo.User;
import lombok.Data;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;

import java.util.Collection;

@Data
public class UserRepos {

    private Collection<User> users ;

    private BeanFactory beanFactory ;

    private ObjectFactory<ApplicationContext> objectFactory ;


}

InjectDemo 

package com.test;

import com.test.anonation.VIP;
import com.test.pojo.User;
import com.test.repos.UserRepos;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * IOC 依赖注入
 */
public class InjectDemo {
    public static void main(String[] args) {

        /**根据名称查找
         */
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/content-inject.xml") ;
        UserRepos userRepos = beanFactory.getBean("userRepos", UserRepos.class) ;

        System.out.println(userRepos.getBeanFactory());
        System.out.println( userRepos.getObjectFactory() );
        System.out.println(  userRepos.getObjectFactory().getObject()== beanFactory  );

    }
}

 

结果

org.springframework.beans.factory.support.DefaultListableBeanFactory@7c7b252e: defining beans [user,objectFactory,vipUser,userRepos]; root of factory hierarchy
org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider@32ee6fee
true