直接看代码:
UserController.java
package spring.beans.annotation.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import spring.beans.annotation.service.UserService; @Controller public class UserController { @Autowired private UserService userService; public void add() { System.out.println("UserController add..."); userService.add(); } }
UserService.java
package spring.beans.annotation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import spring.beans.annotation.repository.UserRepository; import spring.beans.annotation.repository.UserRepositoryImpl; @Service public class UserService { @Autowired @Qualifier("userRepositoryImpl") private UserRepository userRepository; public void add(){ System.out.println("UserService add..."); userRepository.add(); } }
UserRepository.java
package spring.beans.annotation.repository; public interface UserRepository { public void add(); }
UserRepositoryImpl.java
package spring.beans.annotation.repository; import org.springframework.stereotype.Repository; @Repository//("userRepository") //这里设置的value="userRepository",也可以用@Qualifier("userRepositoryImpl")写在装配它的地方 public class UserRepositoryImpl implements UserRepository { @Override public void add() { System.out.println("UserRepositoryImpl add..."); } }
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-4.3.xsd"> <!-- 扫描指定spring IOC容器的类 --> <!--使用resource-pattern扫描特定的类 --> <!-- <context:component-scan base-package="spring.beans.annotation" resource-pattern="repository/*.class"> </context:component-scan> --> <!-- 筛选扫描 --> <context:component-scan base-package="spring.beans.annotation" > <!-- 扫描不包含指定类型(表达式)的类 --> <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- 扫描包含指定类型(表达式)的类(context下设置use-default-filters="false")配合使用 --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- 扫描除了该接口 或该接口实现类的类 --> <!-- <context:exclude-filter type="assignable" expression="spring.beans.annotation.repository.UserRepository"/> --> <!-- 只扫描包含该接口 或该接口实现类的类 (context下设置use-default-filters="false")配合使用--> <!-- <context:include-filter type="assignable" expression="spring.beans.annotation.repository.UserRepository"/> --> </context:component-scan> </beans>
时间: 2024-10-27 07:04:59