标题Spring Hello
pom.xml中导入maven配置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
编写代码,Dao包下实现Hello类
package dao;
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello,"+ name );
}
}
resources目录下创建beans.xml文件,定义bean对象
<?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就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="dao.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
在test目录下创建MyTest.java测试文件
import dao.Hello;
import dao.UserDaoImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
import service.UserServiceImpl;
public class MyTest {
@Test
public void test(){
//解析beans.xml文件 , 生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean : 参数即为spring配置文件中bean的id .
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
}
Hello对象是由Spring创建的,他的name属性也是由spring设置的。
控制指程序代码控制对象的创建变为由spring创建。
反转:程序本身不创建对象,变为接收对象。
依赖注入DI:利用Set方法注入。
IOC创建对象的方式
Spring的IOC默认通过类的无参构造函数来构建对象。
当想使用类的有参构造函数创建对象时,有几种方式:
<constructor-arg index="0" value="value1"/>
<constructor-arg type="java.lang.String" value="value2"/>
<constructor-arg name="name" value="value3"/>
Spring的其他配置
alias 设置别名 , 为bean设置别名 , 可以设置多个别名
<alias name="bean名称" alias="bean别名"/>
直接配置Bean,name可以设置多个通过空格,逗号,分号都可以分隔不同的名称
<bean id="hello" name="hello2 h2,h3;h4" class="dao.Hello">
<property name="name" value="值"/>
</bean>
团队合作可以使用import将不同的xml的bean配置文件合并
<import resource="{path}/beans.xml"/>