自动扫描方式把组件纳入spring容器中管理

spring2.5引入了组件自动扫描机制,
他可以在类路径底下寻找标注了
@Component、@Service、@Controller、@Repository注解的类,
并把这些类纳入进spring容器中管理。

@Service用于标注业务层组件、
@Controller用于标注控制层组件(如struts中的action)、
@Repository用于标注数据访问组件,即DAO组件。

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。


它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,需要打开以下配置信息:
<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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 开启自动扫描机制,并设定扫描的包,以及子表 -->
          <context:component-scan base-package="com.dwt1220"/>
</beans>
beans.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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
         
          <!-- 开启自动扫描机制,并设定扫描的包,以及子表 -->
          <context:component-scan base-package="com.dwt1220"/>
     
</beans>

PersonService.java 接口
package com.dwt1220;

public interface PersonService {
	public abstract void save();
}

PersonServiceBean.java
package com.dwt1220;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("personServicexxx")//设置bean的id。默认类名的第一个字母小写personServiceBean
@Scope("prototype")//设置bean的作用域。默认singleton
public class PersonServiceBean implements PersonService {

	@PostConstruct //设置类的初始化方法,同bean标签的init-method=""设置
	public void init() {
		System.out.println("初始化");
	}

	@PreDestroy//设置类的销毁方法,同bean标签的destroy-method=""设置
	public void destory() {
		System.out.println("关闭资源");
	}

	public void save() {
		System.out.println("personService的save()方法");
		;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dwt1220

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值