?
?
?
其中base-package为需要扫描的包(含所有子包) @Autowired后不需要getter()和setter()方法,Spring也会自动注入 @Qualifier指定注入哪个实现类 @Service用于标注业务层组件 @Controller用于标注控制层组件(如struts中的action) @Repository用于标注数据访问组件,即DAO组件. @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 @Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意)
?
实例解释:
该实例是添加@Component 后,spring在base-package扫描 后,执行afterPropertiesSet方法。
package com.mifi.main;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.mifi.common.Dictionary;
import com.mifi.main.proxy.MifiServer;
/**
* 初始化系统上下文静态常量
*/
@Component
public class Init implements ApplicationContextAware , InitializingBean{
Logger logger=Logger.getLogger(Init.class);
ApplicationContext context;
@Override
public void afterPropertiesSet() throws Exception {
Map<String, Object> _map=context.getBeansWithAnnotation(MifiServer.class);
for (Entry<String,Object> e:_map.entrySet()) {
String name=e.getKey().replace("Impl", "");
Class<?> _clazz=e.getValue().getClass();
MifiServer _ms=_clazz.getAnnotation(MifiServer.class);
if(null!=_ms)
name=_ms.name();
Dictionary.MIFI_SERVICES.put(name,e.getValue());
}
logger.info("["+Dictionary.MIFI_SERVICES.size()+"] server inited ");
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context=context;
}
}
?
?
?
?
?
?
原文:http://knight-black-bob.iteye.com/blog/2256211