Spring's IOC annotation configuration
step
Import one more package in the most basic Spring environment
- spring-aop-4.3.8.RELEASE.jar
Import another constraint , the import method is the same as before
..\spring-framework-4.3.8.RELEASE-dist\spring-framework-4.3.8.RELEASE\schema\context
Import spring-context-4.3.xsd under the path- Note : When importing a Schema constraint, there can only be one empty namespace in the constraint
Enable *spring support for annotations* in the applicationContext.xml configuration file
<!-- 开启spring对注解的ioc支持,对包进行组件扫描 --> <context:component-scan base-package="com"></context:component-scan>
code
- Write annotations in objects
@Component("User")
public class User {
private String name;
private int age;
private Car car;
private Date birthday;
set/get()....
}
- applicaionContext.xml configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd ">
<!-- 开启spring对注解的ioc支持,对包进行组件扫描 -->
<context:component-scan base-package="com"></context:component-scan>
</beans>
- test class
/**
* 测试注解配置能否拿到对象
*/
@Test
public void getUser(){
//获取工厂类
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
User user = (User) context.getBean("User");
System.out.println(user);
}