Spring Dependency Injection constructor injection (through constructor injection)

Source: Internet
Author: User

Build Applicationcontext.xml (Spring Management Bean configuration file) in src directory

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >    <BeanID= "Dog"class= "Com.cc8w.Entity.Dog">        <Constructor-arg>        <value>Wong Choy</value>        </Constructor-arg>        <Constructor-arg>        <value>20</value>        </Constructor-arg>        <Constructor-arg>        <value>Male</value>        </Constructor-arg>    </Bean></Beans>

Data type of 2.java

 Packagecom.cc8w.Entity; Public classDog {PrivateString names; Private intAge ; PrivateString sex;  PublicDog (String names,intAge , String Sex) {        Super();  This. Names =names;  This. Age =Age ;  This. Sex =sex; }     PublicString GetNames () {returnnames; }     Public voidsetnames (String names) { This. Names =names; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }    }

3. Test class

 Packagecom.cc8w;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportCom.cc8w.Entity.Dog; Public classTest01 { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//ApplicationContext Management BeanApplicationContext context =NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Dog Dog= (dog) Context.getbean ("Dog"));        System.out.println (Dog.getnames ());        System.out.println (Dog.getage ());    System.out.println (Dog.getsex ()); }}

Results:

Spring Dependency Injection constructor injection (through constructor 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.