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

  • 相关阅读:
    IIS7.5应用程序池集成模式和经典模式的区别【转】
    Qt keyPressEvent keyReleaseEvent 分析
    cesium编程中级(二)源码编译
    cesium编程中级(一)添加示例到Sandcastle
    cesium编程中级开篇
    cesium编程入门(九)实体 Entity
    cesium编程入门(八)设置材质
    QPushButton 点击信号分析
    cesium编程入门(七)3D Tiles,模型旋转
    cesium编程入门(六)添加 3D Tiles,并调整位置,贴地
  • 原文地址:https://www.cnblogs.com/lh218/p/6551332.html
Copyright © 2011-2022 走看看