spring自动扫描和管理bean


写在前面:对于spring我真的是小白,可我这个小白发现spring越来越强大了。今天说一下spring自动扫描和管理bean.

引入spring注解后,有三种方式分别为@service用于注解服务层;@controller用于注解控制层;@responsity用于注解dao;@component用于注解不好分类的类

这几种注解方式目前而言就是一种规范,实际使用效果没有什么区别。

下面讲解spring注解的case.

bean.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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="springdao"/> <context:component-scan base-package="serviceImpl"/> <!--如果包比较多,可以多次引入--></beans>


personDao.java

@Controller(value="personDao") @scope("prototype")public class personDao { private String name; private String dep; public String getName() { return name; } public void setName(String name) { this.name = name; } public void Test(){ System.out.println("hello,spring"); }}

productCreator.java

@Component(value="productCreator")public class productCreator { @Resource public personDao pDao=null; public productCreator(){ System.out.println("........正在被创建!"); } public static personDao createPersonDao(){ return new personDao(); } @PostConstruct //初始化方法,在类被实例化的时候就会被执行 public void execPdao(){ pDao.Test(); }}

springtest.java

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"}); personDao pe=(personDao)ctx.getBean("personDao"); productCreator pea=(productCreator)ctx.getBean("productCreator"); pe.Test(); pea.execPdao(); }

运行springtest.java得到如下结果:

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn