美文网首页
3.6 @DependsOn

3.6 @DependsOn

作者: 仙境源地 | 来源:发表于2019-10-14 18:01 被阅读0次

chapter03/bean-autowiring

package com.apress.prospring5.ch3.annotated;
import org.springframework.stereotype.Component;
/**
 * Created by iuliana.cosmina on 2/22/17.
 */
@Component("gopher")
public class Guitar {

    public void sing(){
        System.out.println("Cm Eb Fm Ab Bb");
    }
}
package com.apress.prospring5.ch3.annotated;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

/**
 * Created by iuliana.cosmina on 2/22/17.
 */
@Component("johnMayer")
@DependsOn("gopher")
public class Singer implements ApplicationContextAware{
    ApplicationContext applicationContext;

    @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private Guitar guitar;

    public Singer(){
    }

    public void sing() {
        guitar =  applicationContext.getBean("gopher", Guitar.class);
        guitar.sing();
    }
}
<?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="com.apress.prospring5.ch3.annotated"/>
</beans>
package com.apress.prospring5.ch3.annotated;
import org.springframework.context.support.GenericXmlApplicationContext;
/**
 * Created by iuliana.cosmina on 2/23/17.
 */
public class AnnotatedDependsOnDemo {
    public static void main(String... args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("classpath:spring/app-context-02.xml");
        ctx.refresh();
        Singer johnMayer = ctx.getBean("johnMayer", Singer.class);
        johnMayer.sing();
        ctx.close();
    }
}

相关文章

网友评论

      本文标题:3.6 @DependsOn

      本文链接:https://www.haomeiwen.com/subject/lhxdmctx.html