什么是Spring
spring是一个容器框架,用于管理bean,并维护bean之间的关系
Spring核心机制
bean: 可以是java中的任意对象,Spring就是通过管理每一层的bean,来实现管理整个项目:1.管理bean的实例化:对象的诞生;2.管理对象的关系。
IOC(inverse of control)控制反转: 以前,对象都是new出来的,现在即所有对象都是有spring来管理的
DI(dependency injection): 依赖注入
AOP(aspect onented programming): 面向切面编程,面向所有对象编程
Spring在读取application配置文件的时候就被加载了。
第一个Spring程序
工具类
public class HelloWorld {
private String name;
public void setName(String name) {
System.out.println("调用setter方法:"+name);
this.name = name;
}
public HelloWorld() {
System.out.println("调用构造方法");
}
public void hello() {
System.out.println("hello:"+name);
}
}
核心配置文件:applicationContext.xml
<!-- 配置bean-->
<!-- id是拿来表示对象的,class为类名,name为类的属性名,value设置属性的值-->
<bean id="helloworld" class="test.HelloWorld">
<property name="name" value="参数设置位置1">
<!--直接配置name属性的值-->
<!--<value>参数赋值位置2</value>-->
</property>
</bean>
<!--当一个类中的属性为某个对象时-->
<bean id="person" class="test.Person">
<!--对象属性-->
<!--ref的值对应某个bean的id值,即可将该id对应的对象赋给该属性-->
<property name="helloworld" ref="helloworld"></property>
</bean>
当bean的数量过多时,可以直接Spring的配置扫描路径 ,代码如下:
<context:component-scan base-package="test"></context:component-scan>
置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean
测试类
public class Test{
public static void main(String[] args) {
//创建spring的IOC容器对象,读取配置文件,将读取到的bean实例化,放入容器(不考虑bean的生命周期)
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//从IOC容器中根据bean的id值获取bean实例
HelloWorld helloworld = (HelloWorld) ctx.getBean("helloworld");
helloworld.hello();
}
}
运行结果
调用构造方法
调用setter方法:参数设置位置1
hello:参数设置位置1