spring入门5-annotation自动注入

本文介绍Spring框架中如何通过注解实现类的自动监测与Bean的注册过程,包括使用@Component等注解来标记可装配的类,并通过<context:component-scan>进行扫描配置。

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

1.类的自动监测及Bean的注册

Spring 可以自动监测类并注册Bean 到ApplicationContext中

为了能够监测这些类并注册相应的Bean,需要下面内容

<context:component-scan base-pakcage="org.example" >

默认情况下,类呗自动发现并注册bean的条件是:使用@Component,@Repository ,@Service, @Controller注解或者使用@Component的自定义注解


2.

扫描过程中组件被自动监测,那么Bean名称是由BeanNameGenerator生成的 (@Component, @Repository,@Service, @Controller都会有个name属性用于显示设置Bean Name)

默认的是类名,第一个字母小写


3.

通常情况下自动查找的Spring组件,其scope是singleton 。 Spring2.5提供了一个标识scope的注解@Scope, 可以指定@Scope("prototype")


bean 

package annotation;

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

//@Component("bean")
@Scope
@Component
public class BeanAnnotation {
	
	public void say(String arg) {
		System.out.println("BeanAnnotation : " + arg);
	}
	
	
	
}

spring配置文件

<?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.xsd" >
        
        <context:component-scan base-package="annotation"></context:component-scan>
        
 </beans>

测试

package test.annotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import annotation.BeanAnnotation;





@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation{
	
	private ClassPathXmlApplicationContext context;
	
	@Test
	public void testBean(){
		
		 context = new ClassPathXmlApplicationContext("spring-annotation.xml");
		 BeanAnnotation ba = (BeanAnnotation) context.getBean("beanAnnotation");
		 ba.say("11");
	}
	

	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值