zoukankan      html  css  js  c++  java
  • 基于注解初始化IoC容器

    创建s07
    pom.xml文件的依赖不变
    创建applicationContext.xml文件,引入schema。
    基于注解的schema和基于xml的schema不一样
    最典型的是增加了一个名为context的命名空间
    命名空间:就像是java中的包名一样。区分和xml的bean标签
    xmlns:context="http://www.springframework.org/schema/context"
    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    </beans>
    context:component-scan组件扫描。具体的用意是在IoC容器初始化时自动扫描四种组件类型注解并完成实例化@Repository、@Service、@Controller、@Component
    context:component-scan下的属性base-package代表基准包是哪个,扫描哪个包下面所有的类
    设置Dao实现类
    组件类型注解默认beanId为类名首字母小写。此处beanId=userDao
    也可以进行手动设置beanId。注解之后加括号双引号。默认是value属性,例@Repository(" ")
    import org.springframework.stereotype.Repository;
    
    // 用于说明当前对象用于数据持久化。增删改查
    // 组件类型注解默认beanId为类名首字母小写。beanId=userDao
    // 也可以进行手动设置@Repository("")默认是value属性
    @Repository
    public class UserDao {
    }
    IoC容器初始化以后,我们可以将容器内对象打印出来
    context.getBeanDefinitionNames()获取到容器内所有有效的beanId。返回一个id数组。getBean()打印的是bean对象。
            String[] ids = context.getBeanDefinitionNames();
            for(String id:ids){
                System.out.println(id + " ");
            }
    这四类注解都是单例的
  • 相关阅读:
    媒体定律:马航失联客机取代昆明袭击
    讨论世界的意义是否存在
    神与信仰和人的意义
    读《人生哲思录》论“人”与“意义”
    如果人类世界灭亡 幸存者有多少资源
    stagewidth stage.width 区别
    flash的render延迟渲染
    【翻译】自定义 UIViewController Transitions
    [功能]点击ImageView进入页面,时间响应者链实现
    开学面试笔试总结
  • 原文地址:https://www.cnblogs.com/sx1011/p/13676145.html
Copyright © 2011-2022 走看看