IDEA+Maven配置Spring——第一个Spring程序
1、导入依赖
新建一个空的Maven项目,导入spring的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2、配置文件
在resource目录下新建beans.xml,新版的idea都有自带的spring基本配置xml文件
3、新建一个实体类
public class Hello {
private String str;
public Hello(String str) {
this.str = str;
}
public Hello() {
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
4、依赖注入
在建好的beans.xml文件中添加标签
<!--使用Spring来创建对象,在Spring中这些都称为bean-->
<!--id为对象名,class为new的类,name为类属性,value赋值-->
<bean id="hello" class="com.chen.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
5、编写测试类
import com.chen.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");
//我们的对象现在都在spring中管理了,我们要使用,只截取里面取出来即可
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello);
}
}
到这里一个基本的Spring 程序就完成了。实现了基本Spring IOC容器以及依赖注入。