The first example of Spring, the first example of Spring
Spring controls flip IoC, or dependency injection. There is no new object in the test class, and the object is injected from the xml file.
The <beans> in the xml file is a large container, where <bean> is the content in the container, which is an instance object.
We create an object in an xml file, so we don't need to create any more objects in Java. When we use these objects, we can inject them from the xml bean.
1. Create a class
package com.wangcf;public class HelloWorld { private String name; public void sayHello(){ System.out.println("Hello World"+name); } public String getName() { return name; } public void setName(String name) { this.name = name; }}
2. Create an xml file
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: p = "http://www.springframework.org/schema/p" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.s Pringframework.org/schema/aop/spring-aop-3.0.xsd "> <! -- Register a Hello World instance named HelloWorld --> <bean name = "helloworld" class = "com. wangcf. helloWorld "> <property name =" name "> <value> Xiao Ming </value> </property> </bean> </beans>
3. Create a test class
Package com. wangcf; import org. junit. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; public class HelloTest {@ Test public void testSayHello () {// create Spring container ApplicationContext context = new ClassPathXmlApplicationContext ("beans. xml "); // get a bean from the container, that is, an instance object HelloWorld hello = (HelloWorld) context. getBean ("helloworld"); hello. sayHello ();}}
4. output results