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

  • 相关阅读:
    WCF学习笔记1发布使用配置文件的服务
    Oracle(Hierarchical Queries)层级查询
    Telerik UI For WinForms关于RadGridView的列排序
    C#异步显示工作进度
    CodeSmith连接Oracle
    Access数据导入SQLServer2008R2
    Oracle (RANK) 排名函数
    C#INotifyPropertyChanged(解决数据绑定的界面刷新问题)
    Code Complete读书笔记03
    C++ Primer Plus读书笔记08
  • 原文地址:https://www.cnblogs.com/lh218/p/6551332.html
Copyright © 2011-2022 走看看