先准备代码相关
1.先准备相关代码。下面贴工程的pom文件
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gee</groupId>
<artifactId>springframework-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 指定maven编译的jdk的版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.源码自行准备,工程使用的spring版本为5.0.2
3.项目准备
3.1分别建立controller,service,entity几个包,工程结构,如下图所示。
image.png
controller的代码
@Controller
@RequestMapping(value = "/hello")
public class HelloController {
@Autowired
private HelloService helloService;
}
service的代码
public interface HelloService {
public String sayHello();
}
serviceImpl的代码
@Service
public class HelloServiceImp implements HelloService{
@Override
public String sayHello() {
return "say hello";
}
}
最后测试该方法,代码如下
@Configuration
@ComponentScan(basePackages = "com.gee")
public class Config {
public static void main(String args[]) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
System.out.println(applicationContext.getBean(HelloService.class).sayHello());
}
}
执行main方法,最后输出一个"say hello "
网友评论