首页 > 代码库 > Spring基础(9) : 自动扫描

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

 

Spring基础(9) : 自动扫描