Spring入门案例
3.Spring入门案例
1):创建一个maven项目,并导入spring依赖;
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
</dependencies>
2):创建一个实体类,Hello,并重写setter和tostring方法;
package com.yf.pojo;
public class Hello {
private String str;
public void setStr(String str) {
this.str = str;
}
public String getStr() {
return str;
}
3):在resources目录下面创建Spring中的xml配置文件;
bean标签中的代码即表示:创建一个Hello的对象,其对象名为hello,并为对象中的属性str复制为Spring。
4):编写测试类;
package com.yf.Test;
import com.yf.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}