您当前的位置: 首页 >  spring

小志的博客

暂无认证

  • 2浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

spring自定义逻辑返回需要导入的组件——实现ImportSelector接口示例

小志的博客 发布时间:2019-11-19 10:36:53 ,浏览量:2

1、创建一个maven项目(创建maven项目过程省略),pom.xml文件引入如下依赖:


	org.springframework
	spring-context
	5.2.0.RELEASE


	junit
	junit
	4.12
	test

2、创建一个Department的实体类,代码如下:

package com.rf.bean;

public class Department {
	private Integer id;//部门id
	private String dname;//部门名称
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}

	@Override
	public String toString() {
		return "Department [id=" + id + ", dname=" + dname +  "]";
	}
	
	
}


3、创建一个Employee的实体类,代码如下:

package com.rf.bean;

public class Employee {
	private Integer id;
	private String name;
	private Integer age;
	private Integer did; //部门id
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public Integer getDid() {
		return did;
	}
	public void setDid(Integer did) {
		this.did = did;
	}
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", did=" + did + "]";
	}
	
	
	
	
}


4、创建实现ImportSelector接口的MyImportSelector类,代码如下:

package com.rf.condition;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector{
	
	//返回值,就是到导入到容器中的组件全类名
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {
		// TODO Auto-generated method stub
		return new String[]{"com.rf.bean.Employee","com.rf.bean.Department"};
	}

}

5、编写配置类,代码如下:

package com.rf.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.rf.bean.Department;
import com.rf.bean.Employee;
import com.rf.condition.MyImportSelector;

@Configuration
@Import({MyImportSelector.class})
public class MyConfig {

}

6、编写测试类,代码如下:

package com.rf.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.rf.config.MyConfig;

public class Test {
@org.junit.Test	
	public void test04(){
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
		System.out.println("ioc容器创建完成了。。。。");
		
		//获取注册的组件名称
		String[] beanNamesForType = applicationContext.getBeanDefinitionNames();
		for(String name: beanNamesForType){
			System.out.println("获取注册的组件名称-------"+name);
		}
	}

7、启动测试类,运行效果如下: 在这里插入图片描述

关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.0424s