一、环境
- spring-framework-5.1.14.RELEASE
- jdk1.8
- Maven3.6.4
二、用Maven创建项目
创建maven-archetype-quickstart项目
mvn archetype:generate -DgroupId=abc.lei.le -DartifactId=Spring3-Example -DarchetypeArtifactId=maven-archetype-quickstart
三、 编辑 pom.xml,加入 spring 依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>abc.lei.le</groupId>
<artifactId>Spring3-Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring3-Example</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.1.14.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
四、创建一个Spring Bean
一个简单的spring bean如下
package abc.lei.le.helloworld;
public class Helloworld {
private String name;
public void setName(String n){
this.name = n;
}
public void printHello(){
System.out.println("The first Spring :hello" + name);
}
}
五、创建Spring Bean的配置文件
创建文件SpringBeans.xml,配置bean如下。文件位于src/main/resources下
<?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 id = "helloBean" class = "abc.lei.le.helloworld.Helloworld">
<property name = "name" value = "你好666666呀"/>
</bean>
</beans>
六、创建测试App
package abc.lei.le;
import abc.lei.le.helloworld.Helloworld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App{
private static ApplicationContext context;
public static void main(String[] args){
context = new ClassPathXmlApplicationContext("SpringBeans.xml");
Helloworld obj = (Helloworld) context.getBean("helloBean");
obj.printHello();
}
}
运行代码
mvn compile
mvn exec:java -Dexec.mainClass="abc.lei.le.App"
网友评论