File - > New -> other
右击,选择属性,修改成1.8,最终结果
打开:https://mvnrepository.com,搜索 spring context
点开对应版本,找到引入配置内容
具体代码如下:
具体代码如下:
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()+"]跟我联系"); } }
在/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>
具体代码:
package cn.sjxy.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.sjxy.dao.UserDao; import cn.sjxy.domain.User; public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = new User(); user.setName("王志瑞"); user.setMobile("15345187578"); //通过容器获取到bean对象 - 获取的对象通过applicationContext进行配置 UserDao userDao = (UserDao)context.getBean("userDao"); userDao.sayHello(user); } }
如果把配置文件修改成实现1,则获取的就是实现1类的实例。