Inject in the spring configuration file by providing the setter method of the attribute in bean. It achieves a certain degree of loose coupling.
Step 1: Create a Java project-springdemo.
Step 2: import the spring jar package and the commons-logging jar package.
Step 3: Compile Bean
Public class animal {private string category; private string name; private int age; Public String getcategory () {return category;} Public String getname () {return name ;} public int getage () {return age ;}@ overridepublic string tostring () {return "Animal [Category =" + category + ", name =" + name + ", age = "+ age +"] ";}}
Step 4: Compile the spring configuration file (in the src directory)
<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "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"> <bean id = "Panda" class = "CN. ZJ. hz. animal "> <property name =" category "value =" Mammal "/> <property name =" name "value =" panpan "/> <property name =" Age "value = "3"/> </bean> </beans>
Step 5: Compile the test class:
Public class app {public static void main (string [] ARGs) {applicationcontext context = new classpathxmlapplicationcontext ("springconfig. XML "); animal panda = (animal) context. getbean ("Panda"); system. out. println (PANDA );}}
Step 6: Run and view the result:
Animal [Category = mammal, name = panpan, age = 3]
Project Structure: