测试项目的创建
File - > New -> other
右击,选择属性,修改成1.8,最终结果
代码的撰写
pom中引入Spring
打开:https://mvnrepository.com,搜索 spring context
点开对应版本,找到引入配置内容
具体代码如下:
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.sjxy</groupId> <artifactId>chapter02Maven</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.0</version> </dependency> </dependencies> </project>
创建相关的类文件
具体代码如下:
User.java
package cn.sjxy.domain; public class User { private String name; private String mobile; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
UserDao.java
package cn.sjxy.dao; import cn.sjxy.domain.User; public interface UserDao { public void sayHello(User user); }
两个实现类:
package cn.sjxy.daoImpl; import cn.sjxy.dao.UserDao; import cn.sjxy.domain.User; public class UserDaoImpl1 implements UserDao { @Override public void sayHello(User user) { System.out.println("实现1"); System.out.println("大家好,我是["+user.getName()+"],让我们一起学习SSM框架吧"); System.out.println("有任何技术问题,都可以通过电话["+user.getMobile()+"]跟我联系"); } }
package cn.sjxy.daoImpl; import cn.sjxy.dao.UserDao; import cn.sjxy.domain.User; public class UserDaoImpl2 implements UserDao { @Override public void sayHello(User user) { System.out.println("实现2"); System.out.println("大家好,我是["+user.getName()+"],让我们一起学习SSM框架吧"); System.out.println("有任何技术问题,都可以通过电话["+user.getMobile()+"]跟我联系"); } }
创建Spring的主配置文件并进行配置
在/src/main/resoruces目录中创建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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="cn.sjxy.daoImpl.UserDaoImpl2"> </bean> </beans>
测试spring的容器的控制反转功能
具体代码:
package cn.sjxy.Test; import cn.sjxy.dao.UserDao; import cn.sjxy.domain.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class springTest { @Test public void TestIoc() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = new User(); user.setName("王志瑞"); user.setMobile("15345189999"); //通过容器获取到bean对象 - 获取的对象通过applicationContext进行配置 UserDao userDao = (UserDao)context.getBean("userDao"); userDao.sayHello(user); } }
如果把配置文件修改成实现1,则获取的就是实现1类的实例。
最终的项目结构