HelloSpring(第一个Spring程序)
1、环境搭建
需要导入相应的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2、具体操作
1、创建hello类
public class Hello {
private String s;
public Hello() {
}
public Hello(String s) {
this.s = s;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
@Override
public String toString() {
return "Hello{" +
"s='" + s + '\'' +
'}';
}
}
2、配置xml文件(ApplicationContext.xml)
这里的配置文件可以去spring官方文档进行查询
3、使用spring来创建对象
在spring中其所创建的对象都称之为Bean。
3.1bean标签
在使用spring创建对象前我们先学习以下bean标签
其基本语法为:
<bean id="xxx" class="xxx.xxx.xxx.xxx.xxx">
<property name="x" value="xxxxx"/>
</bean>
其中bean代表这是一个bean,其中:
- id属性是bean的标识
- class是这个bean指向的一个类即需要new的对象
- property代表属性
- name代表属性的名称
- value代表的是属性值
下面我们使用Spring来创建hello类,并且为他的属性赋值为“hello,spring”
<bean id="hello" class="com.fan.hello.pojo.Hello">
<property name="s" value="hello,spring"/>
</bean>
这样我们就相当于把hello类托管给了spring
那么我们该如何使用spring来进行创建呢?
3.2实例化一个容器
Spring中提供了一个ApplicationContext构造函数的一条或多条路径是资源字符串,它让容器从各种外部资源加载配置元数据。
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml","xxx.xml");
并且可以使用getBean(String name,Class requiredType)来检索Bean的实例。
下面我们来实例化容器并且来使用容器获取相应的bean。
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello = context.getBean("hello", Hello.class);
System.out.println(hello);
}
这样我们通过spring来获取到了hello的实例,我们可以发现整个过程中我们并没有使用关键字new对hello类进行实例化,spring帮我们做了这些事情。
思考:
-
hello对象是由谁来创建的?
hello是由Spring帮我们创建的。
-
hello的属性是如何设置的?
属性是Spring容器进行设置的
那么这个过程就叫做IOC控制反转
要注意的是,依赖注入是通过set方法来实现的。怎么理解呢?
就是在Spring中对Bean的属性值注入时是通过Set方法来实现的,如果class类中没有set方法则不能实现属性的注入。
是Spring容器进行设置的
那么这个过程就叫做IOC控制反转
要注意的是,依赖注入是通过set方法来实现的。怎么理解呢?
就是在Spring中对Bean的属性值注入时是通过Set方法来实现的,如果class类中没有set方法则不能实现属性的注入。