目录结构:
代码示例:
UserContronller.java
package com.atguigu.spring6.autowired.controller;import com.atguigu.spring6.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserContronller {//注入Service 属性注入@Autowired//根据类型找到对应对象,完成注入private UserService userService;public void add(){System.out.println("controller");userService.add();}
}
UserDao.interface
package com.atguigu.spring6.autowired.dao;public interface UserDao {public void add();
}
UserdaoImpl.java
package com.atguigu.spring6.autowired.dao;import org.springframework.stereotype.Repository;@Repository
public class UserDaoImpl implements UserDao {@Overridepublic void add() {System.out.println("dao");}
}
UserService.interface
package com.atguigu.spring6.autowired.service;public interface UserService {public void add();
}
UserServiceImpl.java
package com.atguigu.spring6.autowired.service;import com.atguigu.spring6.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{
// 注入dao@Autowiredprivate UserDao userDao;@Overridepublic void add() {System.out.println("service");userDao.add();}
}
bean.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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--开启组件扫描功能--><context:component-scan base-package="com.atguigu.spring6"></context:component-scan></beans>
UserTest.java
package com.atguigu.spring6.autowired;import com.atguigu.spring6.autowired.controller.UserContronller;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserTest {@Testpublic void test(){ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");UserContronller userContronller = ac.getBean(UserContronller.class);userContronller.add();}
}
控制台输出
此时Dao包下新增UserDao接口的实现类 UserRedisImpl.java
package com.atguigu.spring6.autowired.dao;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;@Repository
public class UserRedisImpl implements UserDao{@Autowiredprivate UserRedisImpl userRedis;@Overridepublic void add() {System.out.println("Redis dao");}
}
运行报错:
解决方法