您的位置:首页 > 编程语言 > Java开发

Spring静态工厂和扫描器

2015-09-10 16:16 567 查看
<!--*****************************************************************************************-->
<!--静态工厂方法
首先建立一个静态工厂类

public class StaticFactory
{
private static Map<String, persion> maps = new HashMap<String, persion>();

static{
maps.put("p1", new persion());
maps.put("p2", new persion());
}
public static persion getpersion(String name)
{
return maps.get(name);
}
}
-->
<bean id = "staticpersion" class = "com.wsl.StaticFactory" factory-method="getpersion">
<constructor-arg value = "p2"></constructor-arg><!--传入getpersion的参数-->
</bean>
<!--获取实例
persion sPersion = (persion) ctxApplicationContext.getBean("staticpersion");
-->

<!--*****************************************************************************************-->
<!--注解
注解扫描器
@Component    基本注解
@Respository  持久层注解
@Service      业务层组件
@Controller      表现层组件
在当前的spring中 , 这4类注解可以混用, 因为spring无法区分一个类属于哪一层。

需要在xml配置文件中导入context插件
在此之前,需要配置spring扫描器来扫描哪些包
1)<context:component-scan>语句加入

<context:component-scan base-package="com.wsl.anotation"
resource-pattern="/*.class"><!--只扫描特定目录,此例只扫描 com.wsl.anotation下的类,此时不包含子包-->
<!--</context:component-scan>
-->

<!--  autowire resource inject
@Component
public class annonationservice
{

@Autowired
annotation annotation;

@Autowired
@Qualifier("annotation") //用于指定实现类,具体来说就是,当annotation是一个接口
//并且, 系统存在两个或以上的类都实现了这个街口,并且都成为
//了springBean的情况下,接口变量就必须指定一个实现类。
annotation annotation2;

@Autowired//使用设置方法自动装配,跟上面一样,当接口存在多个实现类的时候,那么变量名需写成实现的类名
//自然设置方法构造出来也就是符合条件了
//比如接口annotation , 实现类 annotation2
//在申请接口时annotation annotation2;就可以自动装配annotation2的实现到接口了
public void setAnnotation2(annotation annotation2) {
this.annotation2 = annotation2;
}

public void show()
{
System.err.println(annotation);
System.out.println(annotation2);
}
}

resource inject类似
-->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: