Configuring the Bean by annotations
Spring is able to automatically scan, detect and instantiate components with specific annotations from Classpath.
That is, the way to implement annotations is to configure a bean to meet 2 conditions:
- Classes are labeled with specific components, such as: @Component, @Service, @Repository, @Controller
- Add Bean-scan:<context:component-scan base-package= "Com.pfSoft.annotation" ></context to the configuration file: Component-scan>
The following example illustrates: The New people class, note that the namespace (the previous example has basically omitted the namespace part, but through the Bean-scan to implement annotation-based injection, the namespace is more important)
Package Com.pfsoft.annotation;import org.springframework.stereotype.Component; @Componentpublic 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 () */@Overridepublic String toString () {return ' people [name= ' + name + ' , age= "+ Age +"] ";}}
New interfaces and implementation classes:
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;}}
Test method:
public class Testannotation {applicationcontext ctx=null; @Beforepublic void init () {ctx=new Classpathxmlapplicationcontext ("Spring-annotation.xml");} @Testpublic void Test () {people people= (people) Ctx.getbean ("People");p Eople.setage (8);p eople.setname ("PF"); System.out.println (people); Ipeoplemanservice service= (Ipeoplemanservice) Ctx.getbean ("Peoplemanservice"); if ( Service. Adult (People.getage ())) {System.out.println (Messageformat.format ("{0} adult, {1} years old", People.getname (), People.getage () )); }else {System.out.println (Messageformat.format ("{0} minor, only {1} years old", People.getname (), People.getage ()))}}
The output results are as follows:
People [NAME=PF, AGE=8]PF Minors, only 8 years old
Filtering in the configuration file
Resource-pattern Filter Implementation
<context:exclude-filter type= "annotation" expression= ""/> Child nodes represent target classes to be excluded
<context:include-filter type= "annotation" expression= ""/> Indicates the target class to be included
Spring Framework Learning Notes (10)