1. Use annotations need to import to develop a series of spring package;
2. The need to add a constraint profile: context;
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
3. Configure scanning assembly
<! - annotations in the automatic scan package -> < context: Scan-Component Base-Package = "org.west.pojo" />
4. Write code
package org.west.pojo; import org.springframework.stereotype.Controller; @Controller("stu") public class Student { public String name="喜洋洋"; }
5. Test
public class testor { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student stu = (Student) context.getBean("stu"); System.out.println(stu.name); } }
IOC injection
1. The set method can not provide, can be added directly on a @values attribute name (value);
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; @Controller("stu2") public class Student { @Value("灰太狼") private String name; public String getName() { return name; } }
Such values can also be injected into it.
2. The method set may be added @values (value) set directly on the above method may also be injected into the right value
@Controller("stu2") public class Student { private String name; public String getName() { return name; } @Value("灰太狼") public void setName(String name) { this.name = name; } }
Annotations and XML Comparison
-
xml can be applied to any scene, clear structure.
-
Notes not provide their own class, there are limitations; benefits: the development of simple, convenient