通过 context:component-scan element 配置自动扫描加载Spring Bean

介绍:

在 Spring 3.0 中, 我们有两种方式来配置IOC容器:

  基于XML 的配置方式

  基于Java的配置方式


如果我们采用XML配置文件的方式,那么在比较大的项目中,这个配置文件有可能非常巨大难以维护和管理。 现在我们通过采用Spring的自动探测加载bean的新特性来极大地减少配置文件的大小。


我们可以通过使用 增加 context:component-scan element 配置项,同时在java bean 中使用@component Annotation 来实现我们的目的,


环境要求

JDK 1.5 and Above

Eclipse

spring latest  jars

commons-logging.jar

aopalliance.jar


通过使用@Component annotation 来创建Component

我们可以使用@component annotation 将java Bean 成为 Spring Component


Operator.java

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
29
package com.bsj.componentscan;
 
import org.springframework.stereotype.Component;
 
/**
  * @author Jhothi
  */
@Component( "operator" )
public class Operator
{
  public int add(int i,int j)
  {
  return i+j;
  }
  public int subtract(int i,int j)
  {
  return i-j;
  }
 
  public int multiply(int i,int j)
  {
  return i*j;
  }
 
  public int divide(int i,int j)
  {
  return i/j;
  }
}

我们可以使用 Spring auto wired 特性, 将Operater class 自动注入到下面的 Calculator class 中:

Calculator.java

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
29
30
package com.bsj.componentscan;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
/**
  *
  * @author Jhothi
  */
@Component( "calculator" )
public class Calculator
{
  @Autowired
  private Operator operator;
  public void calculation(int i, int j)
  {
  System.out.println( "i+j : " + operator.add(i, j));
  System.out.println( "i-j : " + operator.subtract(i, j));
  System.out.println( "i*j : " + operator.multiply(i, j));
  System.out.println( "i/j : " + operator.divide(i, j));
  }
 
  /**
  * @param operator the operator to set
  */
  public void setOperator(Operator operator)
  {
  this .operator = operator;
  }
}

注意:

我们可以在component annotation后面的括号里面给该java Bean增加别名/ID.  我们可以在context.getBean()方法中使用此别名/ID

IOC 容器中的配置项

请查看下面例子中的IOC容器中的配置项。 我们可以看到下面两个配置项

<context:component-scan>

<context:annotation-config/> :


1
<context:component-scan base-package= "package1, package2" />

applicationContext.xml:






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值