Spring全注解开发不使用xml文件

  1. 配置类

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    
    //表明为一个配置类
    @Configuration
    //扫描包
    @ComponentScan(basePackages = {"com.dragon"})
    public class ConfigAop {
    }
    

    这里的配置类就相当于我们的xml文件

  2. 声明组件

    import org.springframework.stereotype.Component;
    
    //user0相当于id
    @Component(value = "user0")
    public class User {
        public void add(){
            System.out.println("add添加....");
        }
    }
    

    这里的组件就是标签

    <bean id="user0" class="com.xxx.xxx.User">
    </bean>
    
  3. 测试

    @Test
    public void test(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigAop.class);
        User user = applicationContext.getBean("user0", User.class);
        user.add();
    }
    

    注意这里是 AnnotationConfigApplicationContext,并不是ClassPathXmlApplicationContext
    加载文件是ConfigAop.class,并不是xxx.xml

posted @ 2022-09-02 16:07  DawsonDragon  阅读(71)  评论(0)    收藏  举报