Spring在maven项目结构下的基本配置与使用(idea)
1.在pom文件中添加spring的依赖用来导入spring的jar包,导入依赖代码如下。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2.在resource目录下编写spring配置文件,在导入依赖成功后右键新建文件,点击xml文件类型会有spring.xml的显示,如果没有,刷新maven。
spring配置文件模板如下:
<?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="student" class="org.example.ba01.Student">
<property name="name" value="李四"/>
<property name="age" value="23"/>
</bean>
</beans>
</beans>
3.在两个bean标签之间,编写自己的bean标签,将对象交给spring控制。上面代码将Student的一个对象交给spring控制。加载是spring配置文件中会默认初始化所有的对象。并且通过属性来为对象赋值。具体在代码中使用spring需要先读取spring配置文件,然后获得ApplicationContext的对象,再调用其getbean()方法获得具体的对象。
public void test02(){
String co= "ba01/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(co);
Student student=(Student) ac.getBean("student");
System.out.println(student);
}
4.spring一般是调用类的set函数来为对象赋值,这种方式是叫做设值注入,要求所创建的类需要有set方法。还有一种情况是引用传值,一般出现在类中有属性是其他类的对象。在spring配置文件中,需要用到ref其值是引用类型的bean的id。
<?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="mystudent" class="org.example.ba02.Student">
<property name="name" value="李四"/>
<property name="age" value="23"/>
<property name="school" ref="myschool"/>
</bean>
<bean id="myschool" class="org.example.ba02.School">
<property name="name" value="xiaoxue"/>
<property name="address" value="beijing"/>
</bean>
</beans>
5.除了set设置值之外,还可以通过构造函数进行对象赋值。spring默认调用的是类的无参函数,在创建对象之后在set值。在spring中不使用,改为 来进行赋值处理,会调用类的有参构造函数。
<bean id="mystudent" class="org.example.bat03.Student">
<constructor-arg name="name" value="zhangsan"/>
<constructor-arg name="age" value="20"/>
<constructor-arg name="school" ref="myschool"/>
</bean>
6.除了通过name指定属性的值外,还可以通过index下标来进行,index从0开始,代表构造函数传入的参数,从左往右。标签顺序不影响赋值。一般用name可读性高。
<bean id="mystudent2" class="org.example.bat03.Student">
<constructor-arg index="0" value="lisi"/>
<constructor-arg index="1" value="23"/>
<constructor-arg index="2" ref="myschool"/>
</bean>