标签:
Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。
即,想要实现注解的方式配置bean需要满足2个条件:
以下实例说明:新增People类,请注意命名空间(之前举例的时候都基本都略去了命名空间部分,但是通过bean-scan来实现基于注解的注入时,对于命名空间就比较重要了)
package com.pfSoft.annotation; import org.springframework.stereotype.Component; @Component public class People { private String name; private Integer age; /** * * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * * @return the age */ public Integer getAge() { return age; } /** * @param age the age to set */ public void setAge(Integer age) { this.age = age; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "People [name=" + name + ", age=" + age + "]"; } }
新增接口和实现类:
package com.pfSoft.annotation.service; public interface IPeopleManService { public Boolean Adult(Integer age); }
package com.pfSoft.annotation.service; import org.springframework.stereotype.Service; @Service(value="PeopleManService") public class PeopleManServiceImp implements IPeopleManService { public Boolean Adult(Integer age) { Boolean ret=false; if(age>=18) { ret=true; } return ret; } }
测试方法:
public class testAnnotation { ApplicationContext ctx=null; @Before public void init() { ctx=new ClassPathXmlApplicationContext("spring-annotation.xml"); } @Test public void test() { People people= (People) ctx.getBean("people"); people.setAge(8); people.setName("pf"); System.out.println(people); IPeopleManService service=(IPeopleManService) ctx.getBean("PeopleManService"); if(service.Adult(people.getAge())) { System.out.println(MessageFormat.format("{0}成年了,{1}岁", people.getName(),people.getAge())); } else { System.out.println(MessageFormat.format("{0}未成年,只有{1}岁", people.getName(),people.getAge())); } } }
输出结果如下:
People [name=pf, age=8] pf未成年,只有8岁
resource-pattern实现过滤
<context:exclude-filter type="annotation" expression=""/>子节点表示要排除在外的目标类
<context:include-filter type="annotation" expression=""/>表示要包含的目标类
标签:
原文地址:http://www.cnblogs.com/falcon-fei/p/5456779.html