Spring使用注解管理bean
发布日期:2021-05-07 09:14:14 浏览次数:21 分类:原创文章

本文共 1980 字,大约阅读时间需要 6 分钟。

Spring使用注解管理bean

  1. 通过注解分别创建Dao、Service、controller(servlet),通过给bean上添加某些注解,可以快速将bean加入到ioc容器;

    /*Spring有四个类,在任何类加上任意注解都能快速将这个组件加入ioc容器的管理中		@Controller:控制器,推荐给controller层的组件使用		@Service:业务逻辑,推荐给service层件使用		@Repository:数据库,推荐给Dao层使用		@Component:组件,给不属于以上层使用				步骤:		(1)给要添加的组件上标四个注解的任何一个		(2)告诉spring自动扫描加了注解的组件,依赖context名称空间		(3)一定要导入aop包spring-aop-4.0.0.RELEASE.jar*/package com.atguigu.dao;import org.springframework.stereotype.Repository;@Repositorypublic class BookDao {     }
    package com.atguigu.service;import org.springframework.stereotype.Service;@Service("bookService01")//可以这样自定义id名字public class BookService {     }
    package com.atguigu.servlet;import org.springframework.stereotype.Controller;@Controller@Scope(value="prototype")	//这样写可以开启多实例public class BookServlet {     }
  2. 使用配置文件开启组件扫描

    <?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名称空间	 base-package:指定扫描的基础包,把基础包及它下面的包的所有类,自动扫描进ioc容器中 -->	 <context:component-scan base-package="com.atguigu"></context:component-scan></beans>
  3. 测试

    package com.atguigu.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.atguigu.dao.BookDao;public class AnnotationTest {     	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");		@Test	public void annotation(){     		//id默认就是首字母小写		BookDao bookDao = context.getBean("bookDao",BookDao.class);		BookDao bookDao2 = context.getBean("bookDao",BookDao.class);		System.out.println(bookDao==bookDao2);//true	}	}
上一篇:context:include-filter与exclude-filte控制扫描组件
下一篇:SpEl

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月04日 04时09分20秒