高手的存在,就是让服务10亿人的时候,你感觉只是为你一个人服务......

Spring 自动扫描

目录
  1. 1. component scan
    1. 1.1. demo

Spring容器在对bean进行装配的时候,提供了一套非常方便的方式:自动扫描。


component scan

Spring能够从classpath下自动扫描具有特定注解的组件。

组件如下:
@Component:基本注解
@Respository :建议用在持久层 xxxDaoImpl类上
@Service:建议用在业务层 xxxxImpl类上
@Contoller:建议用在表现层 xxxController类上


demo

需求:获取用户的名字和年龄信息。
Alt text

用户信息model类,@Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.spring.test.model;

import org.springframework.stereotype.Component;

@Component
public class Person {

private String name;

private String ages;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAges() {
return ages;
}

public void setAges(String ages) {
this.ages = ages;
}

}

Controller类:表现层@Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.spring.test.controller;

import org.springframework.beans.factory.annotation.Autowired;

@Controller
public class PersonController {

@Autowired
private PersonService personService;

public void showPersonInfo() {

Person p = personService.getPersonInfo();

System.out.println("姓名:" + p.getName() + "年龄:" + p.getAges());

}

}

Service类,业务层@Service

PersonService 接口:

1
2
3
4
5
6
7
8
9
10
package com.spring.test.service;

import com.spring.test.model.Person;

public interface PersonService {


public Person getPersonInfo();

}

PersonService 实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.spring.test.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

@Service
public class PersonServiceImpl implements PersonService {

@Autowired
private PersonDao personDao;

public Person getPersonInfo() {

return personDao.getPersonInfo();
}

}

Dao类,持久层@Repository

PersonDao接口:

1
2
3
4
5
6
7
8
9
10
package com.spring.test.dao;

import com.spring.test.model.Person;

public interface PersonDao {

public Person getPersonInfo();


}

PersonDao实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.spring.test.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;

@Repository
public class PersonDaoImpl implements PersonDao {
@Autowired
private Person person;

public Person getPersonInfo() {
person.setName("zhangsan");
person.setAges("20");
return person;
}

}

配置文件:spring-component-scan.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">



<context:component-scan base-package="com.spring.test"/>


</beans>

测试:
Alt text