One, no parameter constructor creation
We use spring to create objects of the student class
The Student class declares the following
Packagecom.study.spring; Public classStudent {PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override PublicString toString () {return"Name:" +name+ "\ n" + "Age:" +Age ; }}
The Beans.xml is configured as follows
<?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= "Student"class= "Com.study.spring.Student"> < Propertyname= "Name"value= "Nicholas Zhao Four"></ Property> < Propertyname= "Age"value= "Panax Notoginseng"></ Property> </Bean></Beans>
Using the Bean Factory initialization, the test code is as follows
Packagecom.study.spring;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("\\com\\study\\spring\\beans.xml"); Student Stu= (Student) context.getbean ("Student"); System.out.println (Stu); }}
The results of the implementation are as follows:
Name: Nicholas
Age:37
Summarize
<BeanID= "Student"class= "Com.study.spring.Student"> < Propertyname= "Name"value= "Nicholas Zhao Four"></ Property> < Propertyname= "Age"value= "Panax Notoginseng"></ Property> </Bean>
Configure a Bean,id for the code to get the bean's code name, can not be repeated, class is the type of the classes, including the full package name. Property refers to the attribute name in the class, which is the value assigned to this property.
It is worth noting that the value of the name attribute in the property corresponds to the set method of the property in the class, omitting the prefix set, as set in this article name= "age" actually refers to the configuration of passing a parameter to the Setage method, so the naming should be standardized and named according to the Convention. It is not possible to instantiate without the set method. Direct error.
How the Spring IOC container creates objects