对于扫描到的组件,Spring有默认的命名策略,即第一个字母小写,也可以在注解中通过value属性值标识组件的名称
①第一个注解@Component
import org.springframework.stereotype.Component; @Component public class TestObject { }
②第二个注解@Controller
import org.springframework.stereotype.Controller; //模拟表现层 @Controller public class UserController { public void execute(){ System.out.println("usercontroller execute..."); } }
③第三个注解@Repository
public interface UserRepository { public void save(); } import org.springframework.stereotype.Repository; //模拟表现层 @Repository("userRepository") public class UserRepositoryImpl implements UserRepository { @Override public void save() { // TODO Auto-generated method stub System.out.println("UserRepository save"); } }
<?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-3.1.xsd"> <!-- 指定Spring IOC容器扫描的包 --> <!-- 可以根据resource-pattern来指定扫描的资源 resource-pattern="resposotory/*.class" --> <!-- context:exclude-filter 不包含 --> <!-- <context:component-scan base-package="com.auguigu.spring.beans.annotation"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> --> <!-- context:include-filter 包含 还得将默认的过滤器关掉--> <context:component-scan base-package="com.auguigu.spring.beans.annotation" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> </beans>
base-package属性指定一个需要扫描的基类包
如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类,示例:
<context:component-scan base-package="com.atguigu.spring"
resource-pattern="repository/*.class"></context:component-scan>
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
测试Main
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.auguigu.spring.beans.annotation.controller.UserController; import com.auguigu.spring.beans.annotation.repository.UserRepository; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml"); TestObject testObject = (TestObject) ctx.getBean("testObject"); System.out.println(testObject); UserController uc = (UserController) ctx.getBean("userController"); System.out.println(uc); UserRepository ur = (UserRepository) ctx.getBean("userRepository"); System.out.println(ur); } }
如果需要在一个类中引用另一类,@Autowired 将会在IOC容器中自动装配所需要的bean
@Autowired private UserRepository userRepository; public void add(){ userRepository.save(); System.out.println("userService add"); }