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

  • 相关阅读:
    rn相关文档
    《浅谈我眼中的express、koa和koa2》好文留存+笔记
    (四)Spring 对DAO 的支持
    (三)Spring 之AOP 详解
    (二)Spring 之IOC 详解
    SVN文件上感叹号、加号、问号等图标的原因
    Windows平台下不同版本SVN对比
    eclipse中启动Genymotion模拟器的错误
    (一)问候Spring4
    (十一)Hibernate 高级配置
  • 原文地址:https://www.cnblogs.com/lh218/p/6551332.html
Copyright © 2011-2022 走看看