JavaEE

Spring5基础(6)——Spring Bean(装配方式——

2019-07-25  本文已影响0人  小蜉蝣星蔚

此博客为学习笔记,记录下来怕自己后面学着学着忘记了。 简书内容同步更新,id同名,本文csdn链接

在之前的文章中记录了Spring Bean中的配置属性+实例化+作用域+生命周期,装配方式记录了xml配置文件装配。
此文将Spring Bean的补充Bean装配方式, 这种装配方式更容易拓展,更推荐使用
这是上篇链接:
Spring5基础(5)——Spring Bean(装配方式——xml配置文件装配)

使用注解装配bean
接下来介绍几个常用的注解:

package com.lipiao.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 注解装配
 * 使用@Component
 * 使用@Value
 */
@Component
public class E {
    @Value("dName")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在src下新建annotationContext.xml配置文件,添加以下信息;
通知Spring容器该去com.lipiao.demo这个包下去扫描

<context:component-scan base-package="com.lipiao.demo"/>

在测试类中,使用ApplicationContext类根据配置信息中加载此E类,并打印它的name属性。

ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("annotationContext.xml");
        E e= (E) applicationContext.getBean("e");
        System.out.println(e.getName());

运行效果,控制台打印dName

七月 25, 2019 3:34:52 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4d76f3f8: startup date [Thu Jul 25 15:34:52 CST 2019]; root of context hierarchy
七月 25, 2019 3:34:52 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [annotationContext.xml]
dName

在获取E类实例时: E e= (E) applicationContext.getBean("e"); 是小写开头,小写开头,小写开头
其原因就是:@Component这个注解默认是首字母小写的类名
刚刚代码里的:@Component相当于@Component("e")或者@Component(value="e")
若是一个叫User的类,即@Component("user")或者@Component(value="user"),默认是首字母小写

@Repository@Repository@Controller三者都是将项目结构中某一个层次中的一个类标识为Bean,其功能与@Component一致,只是多了一个对不同层次的标识而已

以上都是对类标注为Bean的,接下来对类中的方法,变量和构造方法进行标注:

demoDao首先查找名字为demoDaoName的bean,如果没找到该类,则以DemoDao类型进行匹配。 同使用@Component时类似,使用@Resource不填写类名则相当于@Resource(name="demoDao")默认小写字母开头的类名

    @Resource(name="demoDaoName")
    private DemoDao demoDaoName;

此处注释相当于@Autowired配合@Qualifier使用名称:

    @Autowired()
    @Qualifier("baseDaoName")
    private DemoDao demoDaoName;

若按照使用@Autowired默认根据Bean类型装配,默认小写字母开头的类名

 @Autowired  
 private DemoDao demoDao;

当然本文只记录了一些基本的东西,更多详细的还有多多看看查阅相关资料。

上一篇 下一篇

猜你喜欢

热点阅读