• Spring 实战-第二章-装配Bean


    Bean是Spring对象的声明(装配wiring),要使用Spring,必须先装配需要使用的对象,有3种装配的方式

    1. 自动化装配Bean
    2. 通过Java代码装配
    3. 通过XML装配
    • 自动化装配Bean

    自动化装配Bean很简单

    1.声明接口

    package soundsystem;
    public interface CompactDisc {
        void play();
    }

    2.添加注解

    
    
    package soundsystem;
    import org.springframework.stereotype.Component;
    @Component
    public class SgtPepper implements CompactDisc {
        private String title ="Sgt. Pepper's Lonely Hearts Club Band";
        private String artist="The Beatles";
        @Override
        public void play() {
            System.out.println("Playing "+ title +" by "+artist);
        }
    }

    @Component表明该类会作为组件类,并告知Spring要为这个类创建Bean。

    3.增加配置,用于连接Bean和接口

    package soundsystem;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    @ComponentScan
    public class CDPlayerConfig {
    
    }

    @Configuration注解表明这个类是一个配置类,该类应该包含在Spring应用上下文中如何创建Bean的细节。

    @ComponentScan能够在Spring中启动组件扫描

    4.测试

    package soundsystem;
    
    import static org.junit.Assert.*;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = CDPlayerConfig.class)
    public class CDPlayerTest {
        @Autowired
        private CompactDisc cd;
        @Test
        public void cdShouldNotBeNull(){
            assertNotNull(cd);
        }
    }

     @Autowired表示会根据配置自动装配

    • 通过Java代码装配Bean

     JavaConfig是配置代码,不应该包含任何业务逻辑,也不应该侵入到业务逻辑代码中,通常会将JavaConfig放到单独的包中。

    对于CDPlayerConfig稍加改造,去掉@ComponentScan注解,意味着关掉了自动扫描,因此会导致无法发现组件,进而导致失败,

    为了解决这个问题在,在代码中显式的声明Bean,这样在使用CompactDisc的时候,会根据配置,使用SgtPeppers类进行初始化。

    package soundsystem;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    public class CDPlayerConfig {
        @Bean
        public CompactDisc sgtPeppers(){
            return new SgtPepper();
        }
    }

    CompactDisc结构非常简单,如果更复杂的结构如何处理呢?

    增加MediaPlayer接口

    package soundsystem;
    public interface MediaPlayer {
        public void play();
    }

    增加CDPlayer类,实现MediaPlayer接口,CDPlayer中有私有属性cd,在play动作时,需要调用cd的play方法

    package soundsystem;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    @Component
    public class CDPlayer implements MediaPlayer {
        @Autowired
        private CompactDisc cd;
    
        @Autowired
        public CDPlayer(CompactDisc cd) {
            this.cd=cd;
        }
    
        @Override
        public void play() {
            cd.play();
        }
    }

    为了能够初始化CDPlayer,需要在CDPlayerConfig中增加一个对应的Bean,使用CompactDisc作为参数来初始化CDPlayer

    package soundsystem;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    public class CDPlayerConfig {
        @Bean
        public CompactDisc sgtPeppers(){
            return new SgtPepper();
        }
        
        @Bean
        public CDPlayer cdPlayer(CompactDisc compactDisc){
            return new CDPlayer(compactDisc);
        }
    }

    测试代码中增加MediaPlayer的测试内容,player增加了Autowired注解,

    初始化的时候,会扫描代码找到可以用的实现(CDPlayer),然后CDPlayer会在CDPLayerConfig(JavaConfig)中找到对应的Bean,并进行初始化

    package soundsystem;
    
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = CDPlayerConfig.class)
    public class CDPlayerTest {
        @Autowired
        private CompactDisc cd;
    
        @Autowired
        private MediaPlayer player;
    
        @Test
        public void playerplay() {
            player.play();
        }
    
        @Test
        public void cdShouldNotBeNull() {
            assertNotNull(cd);
        }
    }
    • 通过XML装配Bean

     spring最初就是通过xml进行配置的,但是对比前面的方法有些缺点,1.配置比较被动,方式比较单一, 2.不灵活,如果改名,可能会导致各种找不到

    首先增加一个配置文件,其中使用了spring相关命名空间,在beans节点中,配置需要bean

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="compactDisc" class="main.java.soundsystem.SgtPepper"/>
        
    </beans>

    然后,由于刚开始学习spring,书中代码并不是很详实,摸索后,直接使用最暴力的方法,仅供展示通过xml装配bean

    package main.java.soundsystem;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    
    public class main {
        @Autowired
        static CompactDisc cd;
        public static void main(String[] args) {
    
            ApplicationContext ctx = new ClassPathXmlApplicationContext(
                    "file:G:\CtripJavaSource\SoundSystem\src\main\resources\testconfig.xml"); // 加载xml文件
            CompactDisc cd = (CompactDisc)ctx.getBean("compactDisc"); // 装配bean
            cd.play();
        }
    }

    这里使用绝对路径方式加载xml,然后进行装配并实例化。

    spring的目录结构和配置读取还不是很清楚,待学习。

  • 相关阅读:
    POST请求
    怎样在ios开发中设置tableview的cell颜色
    error LNK2005 已经在***.obj中定义
    IOS开发之UIView的基本使用
    [置顶] 浅谈Android的资源编译过程
    IOS开发之UIView总结
    鉴别不使用的索引
    浅谈Jquery的使用下篇
    Go如何使用实现继承的组合
    做一个小淘气轮廓--文章和论文专辑
  • 原文地址:https://www.cnblogs.com/lvjianwei/p/7424032.html
Copyright © 2020-2023  润新知