在 classpath 中扫描组件

本文介绍了Spring框架如何通过组件扫描自动管理应用中的类。详细讲述了如何使用@Service、@Repository等注解标记需要由Spring管理的组件,并通过XML配置文件指定扫描的包路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

那spring是怎么来管理的呢,首先它会读取在包pakegeZhuJie
下面的所有类,把需要交给spring容器管理的类纳入spring容器中,那么纳入spring容器中的名称又是什么样的呢,spring里面有一个默认的规则,如果没有给定名称,那么bean的名称就是类的简单名称,简单名称就是类的把类的名称第一个字母变成小写。

@Service用于标注业务层组件,@Controler用于标注控制层组件(如structs中的action),@Repositary用于标注数据访问层组件,即DAO组件,而@Conpoment泛指组件,当组件不好归类的时候用这个注释进行标注。
之前我们用的方式是在xml里面配置bean来告诉spring哪些类需要交给spring管理,而这里呢,首先是扫描我们指定的包里面的这些类,如果这些类里面有这些标注的话,spring就知道,这些类需要交给spring管理。


1.新建一个包,包下放需要管理的类,使用这种需要注意自动扫包的类上要加注解才能扫进来

2.

<?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:p="http://www.springframework.org/schema/p"
	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.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  //xml文件中配置好后自动回扫描该包下的所有类(当然可以用过滤只扫描一部分)
   <context:component-scan base-package="pakegeZhuJie">
   
   </context:component-scan>
   

</beans>
3.
package pakegeZhuJie;

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

import org.springframework.stereotype.Service;

@Service
public class PersonServiceBean{
	public void Save() {
		System.out.println("我怕不会哦");
	}
}

4.

package pakegeZhuJie;

import org.springframework.stereotype.Repository;


@Repository
public class ZhuJietest1{
    public void add(){
        System.out.println("执行PersonDaoBean中的add()方法");
    }
    


}


5.

package pakegeZhuJie;


import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;



public class SpringTest {

   
    public static void setUpBeforeClass() throws Exception {
    }

    @Test 
    public void instanceSpring(){
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        ZhuJietest1 personService = (ZhuJietest1)ctx.getBean("zhuJietest1");
        PersonServiceBean test=(PersonServiceBean)ctx.getBean("personServiceBean");
        personService.add();
        test.Save();
        ctx.close();
        
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值