spring简单理解
首先没有spring之前,基本都是 new 一个对象出来的
用了spring之后,只需把对象放到beans.xml上,就相当于放到一个(IOC)容器,里面的对象就交给spring来管理了
对象
public class Ok{
String name;
}
beans.xml(给对象设置值)
<?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 = "ok" class = "com.he.Ok">
<property name="name" value = "ook" />
</bean>
</beans>
现在可以不需要beans.xml了(通过注解等价于beans.xml)
@Component //等价于<bean id = "ok" class = "com.he.Ok">
public class Ok{
@Value("ook") //等价于<property name="name" value = "ook" />
String name;
}
Spring调用beans中的对象
public class Test {
public static void main(String[] args) {
//1.创建Spring的IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//2.从IOC容器中获取到Bean的示例
Ok ok = (Ok) context.getBean("ok");
//3.进行方法的调用
System.out.println(ok.toString());
}
}