在 classpath 中扫描组件
组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.
特定组件包括:
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称
需要导入aop的包
<?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.0.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.learn.spring" >
</beans>
package com.learn.spring.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.learn.spring.service.UserService;
/**
* 表现层的组件
*
* @Controller的作用:
* 等价于在xml配置文件中: <bean id="userController" class="com.learn.spring.controller.UserController"></bean>
* @Controller注解默认的id值是类名首字母小写,如果想要自己指定,可以使用value属性来指定
* @Controller(value="id") / @Controller("id")
*/
@Controller
//@Component
public class UserController {
}
package com.learn.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.learn.spring.dao.UserDao;
/**
* 业务层的组件
*
*/
@Service
public class UserService {
}
package com.learn.spring.dao;
public interface UserDao {
}
package com.learn.spring.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoJdbcImpl implements UserDao{
}
package com.learn.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.spring.controller.UserController;
import com.learn.spring.dao.UserDao;
import com.learn.spring.service.UserService;
public class TestAnnotation {
public static void main(String[] args) {
//.1实例化ioc容器
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.获取bean
UserController userController =(UserController) ctx.getBean("userController");
System.out.println("userController:" + userController);
// UserService userService = (UserService) ctx.getBean("userService");
// System.out.println("userService: "+ userService);
//
// UserDao userDao = (UserDao)ctx.getBean("userDaoJdbcImpl");
// System.out.println("userDao:" +userDao);
}
}