"Spring Combat"--2 construction Injection

Source: Internet
Author: User

This article explains the construction injection and the basic use of spring, and through an acrobat example, describes the dependency injection properties or how objects are used.

If you want to use spring to implement dependency injection, you need several important steps:

1 defines the primary class and the attributes that need to be detached. Here the main class, refers to the main object of the program, in the example is the Juggler acrobat. and want to separate the structure of the property, it is in the hands of the number of bags beanbags.

2 Configure the Bean.xml. Through the configuration file, determine the relationship between the primary class and attribute, and the implementation class.

3 Get the bean by applying the context, and use it.

Simple injection example, a performer still bag the story.

Instance code:

1 Performer Interface: Performer.java

Package Com.spring.test.action1;  Public Interface Performer {    void  perform () throws performanceexception;}

2 acrobat: Juggler, inherits the performer interface

Package Com.spring.test.action1; Public classJuggler implements performer{Private intbeanbags =3;  Publicjuggler () {} PublicJuggler (intbeanbags) {         This. beanbags =beanbags; }         Public voidperform () throws Performanceexception {System. out. println ("juggler"+beanbags+"beanbags"); }}

3 Spring configuration file: Bean.xml

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><bean id="Duke" class="Com.spring.test.action1.Juggler"> <constructor-arg value=" the"/> </bean></beans>

4 Application context Gets the specified bean

Package Com.spring.test.action1;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean.xml"); Performer Performer= (performer) Ctx.getbean ("Duke"); Try{performer.perform (); } Catch(performanceexception e) {e.printstacktrace (); }    }}

The results of the implementation are as follows:

 beanbags

When the primary class is dependent on the injected object, it is not an attribute.

1 For example, the acrobat above will not only still bag, but also perform poetry, then the object of poetry will need to be injected into the performer's constructor, can be described as the acrobat who will recite poetry: Poeticjuggler

Package Com.spring.test.action1; Public classPoeticjuggler extends juggler{PrivatePoem Poem;  PublicPoeticjuggler (Poem Poem) {super ();  This. Poem =poem; }         PublicPoeticjuggler (intbeanbags,poem Poem)        {super (beanbags);  This. Poem =poem; }         Public voidperform () throws Performanceexception {Super.perform (); System. out. println ("While reciting ...");    Poem.recite (); }}

2 Poetry object: Sonnet29

Package Com.spring.test.action1;  Public class Sonnet29 implements poem{    privatestatic" well mi-mi microphone coax ";          public Sonnet29 () {            }        publicvoid  recite () {        System.  out . println (lines);    }}

3 Bean.xml configuration files are as follows

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><bean id="Duke" class="Com.spring.test.action1.Juggler"> <constructor-arg value=" the"/> </bean> <bean id="sonnet29" class="com.spring.test.action1.Sonnet29"/> <bean id="Poeticduke" class="Com.spring.test.action1.PoeticJuggler"> <constructor-arg value=" the"/> <constructor-argref="sonnet29"/> </bean></beans>

4 main execution code to get the developed bean through the application context

Package Com.spring.test.action1;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean.xml");//Performer performer = (performer) Ctx.getbean ("Duke");Performer Performer1 = (performer) Ctx.getbean ("Poeticduke"); Try {//performer.perform ();Performer1.perform (); } Catch(performanceexception e) {e.printstacktrace (); }    }}

5 implementation results are as follows

January -, - 4: +: $pm Org.springframework.context.support.AbstractApplicationContext preparerefresh Info: Refreshing org[email Protected]35bf8de1:startup Date [Sat Jan -  -: +: $Cst -]; Root of context hierarchy January -, - 4: +: $pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions Info: Loading XML bean Definitions from classpath resource [bean.xml] January -, - 4: +: $pm Org.springframework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Info: Pre-instantiating singletonsinchorg.s[email protected]3401a0ad:defining beans [Duke,sonnet29,poeticduke]; root of factory Hierarchyjuggler thebeanbagswhile reciting ... Well, Mia,

"Spring Combat"--2 construction Injection

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.