Spring是什么?
Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的框架
- Spring的IoC容器降低了业务对象替换的复杂性,提高了组件之间的解耦。
- Spring的AOP支持允许将一些通用任务如安全、事务、日志等进行集中式管理,从而提供了更好的复用。
我们要想用Spring导入jar包或者maven导入依赖就可以使用了。
maven依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
然后我们就可以试着写一个helloSpring了。
首先创建一个实体类Hello:
package com.lyr.pojo;
public class Hello {
private String str;
public void setStr(String str) {
this.str = str;
}
public String getStr() {
return str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
然后再resources中创建一个beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<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">
<!--
new一个对象: 类型 变量名 = new 类型()
id=变量名, class=new 的对象
property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.lyr.pojo.Hello">
<property name="str" value="Spring"></property>
</bean>
</beans>
然后就可以进行测试了,在test中新建一个myTest
import com.lyr.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class myTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
结果:输出了str的tostring,在beans.xml中给str赋值为了Spring
这样一个简单的helloSpring就完事了。