zoukankan      html  css  js  c++  java
  • SpringIOC框架简单实现(注解实现)

    SpringIOC框架简单实现(注解实现)


    前情回顾


    运用注解的方式来实现IOC

    首先,让我们来创建一个Dog类

    @Component("dog")//唯一标识名称
    public class Dog implements Pet{
        @Autowired
        @Value("大狗")
        private String name;
    
        @Override
        public String toString() {
            return name;
        }
        
        public void say(){
            System.out.println("WangWang");
        }
    }
    
    
    • @Component:注名,类同XML中的< bean id="dog" >
    • @Autowrited:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法
    • @Value:注入值,类同XML中的< bean value="..." >

    建立接口

    public interface Pet {
        void say();
    }
    

    建立Person类

    @Component("person")//唯一标识名称
    public class Person {
        @Autowired
        @Value("小狗")
        private String name;
        
        @Autowired
        private Pet pet;
        
        public void KeepPet() {
            System.out.println(name + "和" + pet + "站在树下说:");
            pet.say();
        }
    

    建立SpringConfiguration类
    该类等同于xml文件,具有一样的功能,具体请看代码

    @Configuration//标注该类是配置文件XML
    @ComponentScan("Ex04")//扫描包
    public class SpringConfiguration {
    }
    
    • @ComponentScan:根据定义的扫描路径,把符合扫描规则的类装配到spring容器中
    • @Configuration:定义配置类,可替换xml配置文件
      • 注意:
        @Configuration不可以是final类型;
        @Configuration不可以是匿名类;
        嵌套的configuration必须是静态类;

    建立一个测试类

    @RunWith(SpringJUnit4ClassRunner.class)//自带的集成测试
    @ContextConfiguration(classes = {SpringConfiguration.class})//获取Spring容器
    //@ContextConfiguration(locations = "appkicationContext.xml");//获取XML中Spring容器,和上面的只能二者存一
    public class Test_anno {
        @Autowired
        private Person person;
    
        @Test
        public void test() {
            person.KeepPet();
        }
    }
    
    • @RunWith就是一个运行器
      • @RunWith(JUnit4.class):指用JUnit4来运行
      • @RunWith(SpringJUnit4ClassRunner.class):让测试运行于Spring测试环境
      • @RunWith(Suite.class):一套测试集合
    • 当@ContextConfigurationSpring整合JUnit4测试时,使用注解引入多个配置文件
      • 单个文件:
        @ContextConfiguration(Locations=“classpath:applicationContext.xml”)
        @ContextConfiguration(classes = SimpleConfiguration.class)
      • 多个文件:
        @ContextConfiguration(locations = { “classpath:spring1.xml”, “classpath:spring2.xml” })
    • @ContextConfiguration(locations = "appkicationContext.xml"):获取指定的xml文件,但是和注解方式获取只能二者存一

    测试运行,成功。


    总结

    通过注解方式来实现SpringIOC框架可以更加的便捷,但是相应的也会有一定的弊端,xml和注解方式各有优点,编译者可以自由的选择两种方式或嵌套使用。

    以上就是以注解实现SpringIOC框架,如有错误,麻烦指出,感谢耐心到现在的朋友ᕕ( ᐛ )ᕗ ---By 不断努力的Yang

  • 相关阅读:
    THINKPHP3.2视频教程
    PHPCMS 学习
    PHPCMS 后台学习
    phpcms 模板学习
    二叉树的创建与遍历(链式存储)
    MySQL基础~~增、删、改、简单查
    队列的基本操作(链队列)
    MySQL基础~~表结构操作
    行编辑程序
    循环链表的基本操作
  • 原文地址:https://www.cnblogs.com/LaChlanYang/p/14698834.html
Copyright © 2011-2022 走看看