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!