Spring 第一个程序
Spring 第一个程序
1.导入pom依赖:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
3.新建一个pojo类:
package com.xiaofu.pojo; public class Hello { private String str; public String getStr() { return str; } public void setStr(String str) { this.str = str; } @Override public String toString() { return "Hello{" + "str='" + str + '\'' + '}'; } }
2.编写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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--使用spring来创建对象,在spring这些都称为bean--> <!--一个bean就相当于一个对象--> <!--property 相当于给属性设置值 name 类的属性名 value 给属性设置的值--> <bean id="hello" class="com.xiaofu.pojo.Hello"> <property name="str" value="Spring"/> </bean> </beans>
现在刚刚创建的类 就已经被spring管理了
3.使用容器来使用对象:
新建一个测试类来使用一下spring的容器:
代码:
import com.xiaofu.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Text { public static void main(String[] args) { //获取spring的上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //我们的对象现在都在spring容器中管理了,我们要使用,直接去里面取出来就可以了! Hello hello = (Hello) context.getBean("hello"); //这的hello 对应的就是beans.xml文件中的bean标签的id System.out.println(hello.toString()); } }
运行一下:
可以看到 并没有 new一个Hello对象 我们设置和拿到的类的属性
4.IOC创建对象的方法:
默认使用无参构造创建对象
如需要使用有参构造创建对象
<bean id="user" class="cn.pinked.pojo.User"> <!--无参构造 <property name="name" value="张三"/>--> <!--有参下标赋值 <constructor-arg index="0" value="张三"/>--> <!--有参类型赋值 <constructor-arg type="java.lang.String" value="张三"/>--> <!--有参通过参数名赋值 <constructor-arg name="name" value="张三"/>--> </bean>