在classpath中扫描bean组件
组件包括
》@Component:基本注解,标识一个受spring管理的bean组件
》@Controller:标识控制层bean组件
》@service:标识业务层bean组件
》@Repository:标识持久层bean组件,也就是dao层
》@Autowired:自动装配(相当于new了一个)
还有@Resouce、@inject这里就不做一一讲解了。
对扫描到的组件有默认的命名策略类,也就是驼峰命名规则。
比如在class PwqFcxz类上面加一个@Component,那么这个bean的id为pwqFcxz。
也可以不使用默认命名,使用value值,自己命名如:@Controller(value="qwe"),那么要获得这个class时,就要使用qwe获得
下面写上实例代码:
创建一个名为spring4-2-test的web项目
目录结构如下
MyController为控制层,Myservice为业务层,MyDao为持久层,Person为实体类,ScanMain为测试类,applicationcontext-scan.xml为全局配置文件,lib为导入的jar。
Person为实体类:
package com.spring.beans.scan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class MyDao {
@Autowired
Person person;
public void insert() {
person.say();
System.out.println("在数据库中添加成功");
}
}
MyController为控制层:
package com.spring.beans.scan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
@Autowired
MyService service;
public void execute() {
service.insert();
}
}
Myservice为业务层:
package com.spring.beans.scan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
MyDao dao;
public void insert() {
dao.insert();
}
}
MyDao为持久层:
package com.spring.beans.scan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class MyDao {
@Autowired
Person person;
public void insert() {
person.say();
System.out.println("在数据库中添加成功");
}
}
applicationcontext-scan.xml为全局配置文件:
<?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.3.xsd">
<context:component-scan base-package="com.spring.beans.scan"></context:component-scan>
</beans>
运行结果