建立spring helloword工程
1.建立maven工程
命名为spring-helloword;
2.导入依赖
<dependencies>
<!--webmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--lombok 依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
3.建立helloword类
@Data:注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。
需要导入Lombok依赖包才能用@Data注解;
4.建立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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="com.example.dao.HelloWord">
<property name="str" value="Spring"/>
</bean>
</beans>
其中bean中的id对应下面MyTest文件中的getBean;class对应HelloWord类的路径;name是HelloWord类中对应的属性;
value是bean对HelloWord类中属性str的赋值,HelloWord类中只需对属性str声明,初始化是在bean中处理的,即spring在底层处理。
5.建立Test文件
public static void main(String[] args) {
//获取spring的上下文对象,
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//对象在spring中管理了,要使用,就去里面取出来。
HelloWord hello = (HelloWord) context.getBean("hello");
System.out.printf(hello.toString());
}
通过ClassPathXmlApplicationContext读取applicationContext.xml配置文件;其中getBean对应 applicationContext.xml文件中bean的id;