使用Spring输出 Hello,Spring
1.导入的依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.14.RELEASE</version>
</dependency>
</dependencies>
编写类
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 + '\'' +
'}';
}
}
添加对应的xml文件
<?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 = 对象 new hello();
id = 变量名;
class = 全路径
property =给属性设置值
-->
<bean id="hello" class="cn.aguoke.pojo.Hello">
<property name="str" value="Hello,Spring"/>
</bean>
</beans>
在使用Spring是我们不需要创建对象,但必须有对应的set方法
测试
public static void main(String[] args) {
//获取Spring上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在Spring中管理了,使用的话去里面去取就可以了。
Object hello = context.getBean("hello");
System.out.println(hello);
}