一、环境
1. idea2018.1
2.maven 3.3.3
3. jdk1.8
二、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.ygq</groupId>
<artifactId>spring_03_ annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--spring核心库-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring整合Junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
三、项目结构
四、实现步骤
1、spring核心配置文件相当于bean.xml
package com.ygq.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //声明为spring配置文件
@ComponentScan("com.ygq") //开启包扫描
public class SpringConfiguration {
}
2、StudentSerivice.java
package com.ygq.service;
public interface StudentSerivice {
String sayHello();
}
3、StudentSeriviceImpl.java
package com.ygq.service.impl;
import com.ygq.service.StudentSerivice;
import org.springframework.stereotype.Service;
@Service //bean
public class StudentServiceImpl implements StudentSerivice {
public String sayHello() {
System.out.println("I'm StudentServiceImpl!");
return null;
}
}
4、StudentController.Java
package com.ygq.controller;
import com.ygq.service.StudentSerivice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller //bean
public class StudentController {
@Autowired
private StudentSerivice studentSerivice;
public String sayHello(){
studentSerivice.sayHello();
return "I'm StudentController!";
}
}
5、测试类
package com.ygq.controller;
import com.ygq.config.SpringConfiguration;
import com.ygq.service.StudentSerivice;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class) //关键在这里,换成了配置类
public class testStudentController {
@Autowired
private StudentController studentController;
@Test
public void testSayHello() {
System.out.println(studentController.sayHello());
}
}
结果
I'm StudentServiceImpl!
I'm StudentController!