Detailed description of JSP Spring Automatic Assembly Bean instance, springbean

Source: Internet
Author: User

Detailed description of JSP Spring Automatic Assembly Bean instance, springbean

Spring automated Bean assembly

Declare a cd interface:

public interface CompactDisc {  public abstract void play();}

Implement the cd interface:

@Component("SgtPeppers")public class SgtPeppers implements CompactDisc {  private String title = "Sgt.Pepper's Lonely Hearts Club Band";  private String artist = "The Beatles";  @Override  public void play() {    System.out.println("playing" + title + " by " + artist);  }}

Declare cdplayer:

@ Component ("CDplayer") // indicates that this class is used as a Component class and configuration Bean instance is unnecessary, the component name public class CDPlayer {/** @ Autowired annotation in parentheses can be used on the constructor or the set method, it can also be directly put in the following code. * spring will satisfy the dependencies with this annotation. If only one bean matches the dependency requirement, this bean will be assembled. @ Autowired is assembled by type by default. **/@ Autowired private CompactDisc cd; public CompactDisc getCd () {return cd;} public void setCd (CompactDisc cd) {this. cd = cd;} public void play () {cd. play ();}}

Test class:

public class CDPlayerTest {  public static void main(String[] args) {    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");    CDPlayer cdPlayer= (CDPlayer) context.getBean("CDplayer");    cdPlayer.play();  }}

Xml: automatically scans packages to find annotation classes.

<context:component-scan base-package="com.xue.soundsystem"></context:component-scan>

Summary: @ Component: equivalent to adding an instance to the bean of xml, with the id in the brackets. @ Autowired searches for matched instances by type for matching. @ Resource can be assembled by name.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.