您的位置:首页 > 编程语言 > Java开发

spring注解

2016-06-12 21:16 525 查看
一、使用spring注解来构造IOC容器

    1)、在applicationContext.xml配置扫描注解包

        <context:component-scan   base-package="com.test.*"/> 其中base-package指定包名

    2)、如果某类上有注解(@Controller/@Service/@Repository/@Component)等,就会将这个对象作为Bean注册到spring容器

二、注解使用注册Bean

    1)、@Component是使用spring管理注解的通用形式(表示层、业务层、持久层)

    2)、@Controller注册表示层的Bean

        @Controller

        @RequestMapping("/userAction")

        public class UserAction extends BaseAction<User> {

             //coding......

        }

        使用@Controller注解表示Action之后,就表示把UserAction交给Spring容器管理,项目启动后,在Spring容器中会存在一个名字为"userAction"(默认)的action,也可以通过value来设置。@RequestMapping是request请求是的访问路径

    3)、@Service注册业务层Bean

        @Service("userService")

        public class UserServiceImpl implements UserService {

    //coding......

        }

        @Service("userService")注解告诉Spring,当要创建UserServiceImpl实例时,名字必须为"userService",这样当Action要使用UserServiceImp实例时,就由Spring创建好的         UserService注入到Action,示例如下:

        //注入userService

        @Resource(name="userService")

        private UserService userService;

    4)、@Repository注册数据持久层Bean

        @Repository("userDao")

        public class UserDaoImpl extends BaseDao<User> {

            //coding......

        }

        @Repository("userDao")注解告诉Spring,让Spring创建名为"userDao"的UserDaoImpl实例,当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl      实例时,就可以使用@Resource("userDao")注解告诉Spring,Spring把创建好的userDao注入给Service,示例如下:

     @Resource(name="userDao")

     private UserDaoImpl userDao;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: