看完以下内容接着看:https://blog.csdn.net/lgz0921/article/details/104634032
解释都在注释里面~
目录结构:
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">
<parent>
<artifactId>spring-study</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-01-ioc1</artifactId>
</project>
UserDao
package com.kuang.dao;
public interface UserDao {
void getUser();
}
UserDaoImpl
package com.kuang.dao;
public class UserDaoImpl implements UserDao {
public void getUser() {
System.out.println("默认获取用户的数据");
}
}
UserDaoMysql
package com.kuang.dao;
public class UserDaoMysql implements UserDao {
public void getUser() {
System.out.println("ncbacyuabs");
}
}
UserService
package com.kuang.service;
public interface UserService {
void getUser();
}
UserServiceImpl
package com.kuang.service;
import com.kuang.dao.UserDao;
import com.kuang.dao.UserDaoImpl;
import com.kuang.dao.UserDaoMysql;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void getUser() {
userDao.getUser();
}
}
beans.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">
<!--使用Spring来创建对象,在Spring中这些都称为bean-->
<bean id="UserDaoImpl" class="com.kuang.dao.UserDaoImpl"/>
<bean id="UserDaoMysql" class="com.kuang.dao.UserDaoMysql"/>
<bean id="UserServiceImpl" class="com.kuang.service.UserServiceImpl">
<!--
ref:引用Spring中创建好的对象
value:具体的值,基本数据类型
-->
<property name="userDao" ref="UserDaoMysql"/>
</bean>
</beans>
Mytest
import com.kuang.dao.UserDaoImpl;
import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext,拿到Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//容器在手,天下我有,需要什么,直接get社么!
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}