Spring bean在不同情况下的默认id或name 侵立删

转自:https://www.cnblogs.com/1540340840qls/p/6962777.html


 bean如果不知名id是什么它一般都有一个id或者讲名字。

第一种情况:组件扫描的情况:默认的id号或者bean的name是类名的首字母小写。

代码如下:

复制代码
 1 package com.qls.beanlife2;
 2 
 3 import org.springframework.beans.factory.BeanNameAware;
 4 import org.springframework.stereotype.Component;
 5 
 6 /**
 7  * Created by ${秦林森} on 2017/6/7.
 8  */
 9 @Component
  //BeanNameAware这个接口可以获取bean的名字。
10 public class Teacher implements BeanNameAware { 11 @Override 12 public void setBeanName(String name){ 13 System.out.println("the Teacher bean name is : "+name); 14 } 15 }
复制代码

第二种情况:是基于javaConfig显示配置bean时:这个时候bean默认的名字是与方法名相同。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package  com.qls.laowei;
 
import  org.springframework.context.annotation.Bean;
import  org.springframework.context.annotation.Configuration;
 
/**
  * Created by ${秦林森} on 2017/6/8.
  */
@Configuration
public  class  OrderConfig {
     @Bean
     public  Rice getRice(){
         return   new  Rice();
     }
}

Rice类的代码如下:

复制代码
 1 package com.qls.laowei;
 2 
 3 import org.springframework.beans.factory.BeanNameAware;
 4 import org.springframework.stereotype.Component;
 5 
 6 import java.util.List;
 7 import java.util.Map;
 8 import java.util.Set;
 9 
10 /**
11  * Created by ${秦林森} on 2017/6/7.
12  */
13 public class Rice implements BeanNameAware{
14    
15     @Override
16     public void setBeanName(String name) {
17         System.out.println("the rice's bean name is : "+name);
18     }
19    
20 }
复制代码

检验bean的名字为方法名getRice代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package  com.qls.test;
 
import  com.qls.laowei.OrderConfig;
import  com.qls.laowei.Rice;
import  org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
/**
  * Created by ${秦林森} on 2017/6/8.
  */
public  class  Test5 {
     public  static  void  main(String[] args) {
         AnnotationConfigApplicationContext ac =  new  AnnotationConfigApplicationContext(OrderConfig. class );
         Rice rice = ac.getBean(Rice. class );
     }
} /**output:
  the rice's bean name is : getRice
  */

从上面的输出结果可以看到bean在javaConfig的显性配置下即用@Bean的注解的情况下bean的名字为其方法名。

  第三种情况:

在配置文件xml中的配置:<bean class="com.qls.Hello"/>

这个bean的id号默认是com.qls.Hello#0即(包名.类名#自然数)

这个默认id的证明思路与上述两种情况一样,故不赘述。


猜你喜欢

转载自blog.csdn.net/qq_22167989/article/details/81045580