Spring notes-Configuring beans with annotations (annotation)

Source: Internet
Author: User

Spring is able to automatically scan, detect, and instantiate components with specific annotations under Classpath, which is a component scan (Component scanning) in spring.

annotations for specific components include:

@Component: A basic note that identifies a component that is managed by spring.

@Repository: Identifying durable layer components

@Service: Identify service layer (business layer) components

@Controller: Identify presentation layer components

For components on a scan, spring has a default naming policy, using unqualified class names, the first letter lowercase, or the name of the component in the annotations through the Value property values.

When a particular annotation is used on a component, it is also required to be declared in the Spring configuration file:

<base-package= "Com.wang"  resource-pattern= "Dao/*.class" ></ Context:component-scan >

Where Bese-package is a required property, Resource-pattern is an optional property

Bese-package: Develop a base class package that needs to be scanned the spring container will scan all classes in the base class package and its subclass package. When you need to scan multiple packages, you can use commas to separate them.

Resource-pattern: If you want to scan only specific classes, not all classes under the base package, you can use this property to filter specific classes. As above, it means scanning only the Com.wang child packages all classes in DAO.

Component assembly:

The <context:component-scan> element also automatically registers the Autowiredannotationbeanpostprocessor instance, which can be automatically assembled with @autowired, @Resource, @ The properties of the inject annotation.

To automatically assemble beans using @autowired:

@Autowired annotations automatically assemble a single bean attribute with a compatible type :

    Constructors , normal fields , all methods that have parameters can be used @autowired

By default, all properties that use @autowired annotations need to be set, and when spring cannot find a matching Bean assembly property, an exception is thrown, and if a property is allowed to be set, the @autowired annotation can be set Required=false

By default, when more than one type-compatible bean exists in an IOC container, automatic assembly by type will not work, and the bean name can be provided in @Qualifier annotations .

@Autowired annotations can also be applied to array types, collection properties, and map types.

Here is an example to apply the above knowledge points, package structure and class, is a simple MVC structure of user implementation and deletion of the example:

User class:

// main presentation annotations, where attributes are no longer defined  Public class User {}

Userdao Interface:

 Public Interface Userdao {    publicvoid  Add ();      Public void Delete ();      Public void update ();      Public void search ();}

Userdaoimpl class:

@Repository Public classUserdaoimplImplementsUserdao {@Override Public voidAdd () {System.out.println ("Add Users"); } @Override Public voidDelete () {System.out.println ("Delete User"); } @Override Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Update User"); } @Override Public voidsearch () {System.out.println ("Query User"); }}

UserService class:

@Service Public classUserService {@AutowiredPrivateUserdao Userdao;  Public voidAdd () {userdao.add (); System.out.println ("Service Add ..."); }     Public voidDelete () {userdao.delete (); System.out.println ("Service Delete ..."); }     Public voidUpdate () {userdao.update (); System.out.println ("Service Update:"); }     Public voidsearch () {userdao.search (); System.out.println ("Service Search:"); }}

Useraction class:

@Controller Public classuseraction {@AutowiredPrivateUserService UserService; @Autowired (Required=false)    Privateuser User;  PublicString Add () {userservice.add (); System.out.println ("Useraction Add..");        SYSTEM.OUT.PRINTLN (user); return NULL; }     PublicString Delete () {userservice.delete (); System.out.println ("Useraction Delete ..."); return NULL; }     PublicString Update () {userservice.update (); System.out.println ("Useraction Update:"); return NULL; }     PublicString Search () {userservice.search (); System.out.println ("Useraction search ..."); return NULL; }    }

Configuration file Beans.xml:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd/http Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd/HTTP Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd " >   
<Context:component-scan base-package= "Com.wang" />

</beans>

Test code:

 Public class Test1 {    publicstaticvoid  main (string[] args) {        ApplicationContext CTX=new classpathxmlapplicationcontext ("Beans.xml");            Useraction useraction= (useraction) ctx.getbean ("Useraction");    Useraction.add ();        }}

Printing results:

Add user
Service add:
Useraction Add:
Null

Because we did not add any annotation information in the user class, and when we defined the property user in the Useraction class, we added the required= "false" in @autowired, all the printed user is null.

Spring notes-Configuring beans with annotations (annotation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.