zoukankan      html  css  js  c++  java
  • Spring基础(9) : 自动扫描

    一  配置xml方式:扫描com包下的bean

    <?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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com"/>
    
    </beans>
    

      com包下一个类:

    @Component
    @PropertySource("p.properties")
    public class Person {
    
        @Value("${name}")
        public String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

     resource下 p.properties中的文件内容:

    name=hahadaxiao
    

      main函数:

    public static void main(String[] args){
    ApplicationContext context = new ClassPathXmlApplicationContext("a.xml");
    Person p = context.getBean("person",Person.class);
    System.out.println(p.name);
    }

      打印:

    hahadaxiao

    二 注解方式

    com包下存在下面这个类,默认扫描Config1所在的包下的Bean

    @Configuration
    @ComponentScan
    public class Config1 {
    
    }
    

     

    @Component
    @PropertySource("p.properties")
    public class Person {
    
        @Value("${name}")
        public String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

      

    public static void main(String[] args){
            ApplicationContext context = new AnnotationConfigApplicationContext(Config1.class);
            Person p = context.getBean("person",Person.class);
            System.out.println(p.name);
        }
    

      打印:

    hahadaxiao

  • 相关阅读:
    【转】大内高手—内存管理器
    [转]内存泄漏测试小工具 LeakDiag
    [转]内存泄漏测试小工具 LeakDiag
    (转)SplitContainer 控件(Windows 窗体)
    (转)c++内存分配优先使用内存池,而不是new,delete
    (转)C++内存池
    LeakDiag 使用注意
    Struts Validator验证器使用指南
    oracle JOB样例
    oralce杀session
  • 原文地址:https://www.cnblogs.com/lh218/p/6551332.html
Copyright © 2011-2022 走看看