1. 程式人生 > >java中藉助Spring獲取所有帶有指定註解的介面、類、物件-續集

java中藉助Spring獲取所有帶有指定註解的介面、類、物件-續集

1、支援通過Spring的xml配置檔案來制定要獲取註解類的包,如何獲取配置檔案的引數:

/**
* 通過依賴注入獲取配置檔案中的屬性值
* @param basePackages
*/
@Resource
public void setBasePackages(String... basePackages) {
	this.basePackages = basePackages;
}

2、Spring的xml配置檔案:
<bean class="com.lvbey.service.ServiceBean" scope="singleton">
	<!-- 自動掃描的包 -->
	<property name="basePackages">
		<list>
			<value>com.xxxx.service</value>
			<value>com.wwww.service</value>
		</list>
	</property>
</bean>

3、由於在某些情況下,我們不想把擁有@Service的某些類(少數部分)獲取出來,我們可以加上一個自定義註解:@NotAutowired2Service

所以,我們需要自己寫一個自定義的註解類:

/**
 * 在某個類上添加了該註解後,將不會自動注入到需要被獲取的service中
 * @author Lvbey
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotAutowired2Service {
}
好了,現在我們支援從配置檔案獲取指定的包,支援自定義註解了,說了這麼多,直接上原始碼:
package com.lvbey.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.osgi.service.component.annotations.Component;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;

import com.lvbey.service.util.ClassUtil;


/**
 * @author Lvbey
 */
@Component //交給spring管理方便其他類獲取該類物件
@Scope(value="singleto")//單例
public class ServiceBean implements ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	/**
	 * 獲取到的類的例項物件
	 */
	private Map<String, Object> classInstances;
	
	
	/**
	 * 待掃描的基礎包名
	 */
	private String[] basePackages;
	
	
	/**
	 * 通過依賴注入獲取配置檔案中的屬性值
	 * @param basePackages
	 */
	@Resource
	public void setBasePackages(String... basePackages) {
		this.basePackages = basePackages;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	

	public void init(){
		if(this.applicationContext == null){
			return;
		}
		if(this.classInstances == null){
			this.classInstances = new HashMap<String,Object>();
		}
		//獲取有NotAutowired2Service註解的例項
		Map<String, Object> beansWithNotAutowired2ServiceMap = this.applicationContext.getBeansWithAnnotation(com.lvbey.service.annotation.NotAutowired2Service.class);
		
		Map<String, Object> beansWithAnnotationMap = this.applicationContext.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
		
		Class<? extends Object> clazz = null;
		for(Map.Entry<String, Object> entry : beansWithAnnotationMap.entrySet()){
			clazz = entry.getValue().getClass();//獲取到例項物件的class資訊
			Class<? extends Object>  [] interfaces = clazz.getInterfaces();
			for(Class<? extends Object>  aInterface : interfaces){
				String aInterfaceName = aInterface.getName();//介面的完整名
				for(String packageName : this.basePackages){
					if(aInterfaceName.startsWith(packageName)){//如果這個介面是在指定的包下
						
						//介面例項名(只是將介面的首字母換成小寫)
						String aInterfaceSimpleName = ClassUtil.getDefaultInstanceName(aInterface);
						
						//如果這個介面沒有NotServiceBean註解
						if(beansWithNotAutowired2ServiceMap.containsValue(entry.getValue())){
							System.out.println(entry.getValue() + " has NotAutowired2Service Annotation");
						}else{
							classInstances.put(aInterfaceSimpleName, entry.getValue());
						}
					}
				}
			}
		}
	}

	public Map<String, Object> getClassInstances() {
		if(this.classInstances == null){
			init();
		}
		return this.classInstances;
	}
}



裡面用到了一個util工具類:
public class ClassUtil {
	/**
	 * 根據這個類來獲取預設的例項名(預設:將首字母換成小寫)
	 * 
	 * @param clazz
	 *            類資訊
	 * @return 預設的例項名
	 */
	public static String getDefaultInstanceName(Class<?> clazz) {
		if (clazz == null) {
			return null;
		}
		String className = clazz.getSimpleName();
		String firsrLowerChar = className.substring(0, 1).toLowerCase();
		className = firsrLowerChar + className.substring(1);
		return className;
	}
}

然後怎麼使用這個類呢?很簡單,在你需要使用的那個類裡面加上Spring的自動注入就行:

@Autowired
private ServiceBean serviceBean;
serviceBean.getClassInstances() ;//獲取得到的map集合,剩下的想幹啥幹啥

對於不想寫程式碼,想直接使用的看官。。。。。。輕戳下載原始碼.jar