环境准备
- maven
- jdk
- Spring
- Eclipse
项目创建
pom.xml
<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>com.cyb</groupId> <artifactId>spring</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- spring 核心组件中的4个依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.0.7.RELEASE</version> </dependency> <!-- 单元测试Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <finalName>spring</finalName> <plugins> <!-- 配置Maven的JDK编译级别 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
applicationContext.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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.cyb.service"></context:component-scan> </beans>
UserService.java
package com.cyb.service; public interface UserService { void speak(); }
UserServiceImpl.java
其他注解:@Component、@Controller、@Service、@Repository
package com.cyb.service; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Override public void speak() { System.out.println("陈彦斌博客:https://www.cnblogs.com/chenyanbin/"); } }
TestUserService.java
package com.cyb.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cyb.service.UserService; public class TestUserService { @Test public void TestIoc() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService service1 = context.getBean(UserService.class); service1.speak(); } }