美文网首页
Spring的注解注入机制与XML注入机制

Spring的注解注入机制与XML注入机制

作者: SYFHEHE | 来源:发表于2018-12-25 13:24 被阅读0次

1. XML注入方式

其逻辑就是用XML形式可以在配置文件中,配置我们自己写的类和外部库的类,Spring通过反射可以把这些类都创建出来,并由Spring管理,在你需要的时候给你。
步骤
1.在applicationContext.xml文件中配置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" 
       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.example.demo"></context:component-scan>

    <bean id="redSox" class="com.example.demo.entity.RedSox"></bean>
    <bean id="cubs" class="com.example.demo.entity.Cubs"></bean>
    
    <bean id="game" class="com.example.demo.entity.BaseBallGame">
        <property name="awayTeam" ref="redSox"></property>
        <property name="homeTeam" ref="cubs"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean> 
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"/>

</beans>

2.在Java类中添加类的get/set方法——set注入

public interface Team {
    String getName();
}

public class RedSox implements Team {   
    @Override
    public String getName() {
        return "Boston red sox";
    }
}

public class Royals implements Team {
    @Override
    public String getName() {
        return "Kansas City Royals";
    }
}

public class Cubs implements Team {
    @Override
    public String getName() {
        return "Chicago Cubs";
    }
}

public interface Game{
    void setHomeTeam(Team team);
    Team getHomeTeam();
    void setAwayTeam(Team team);
    Team getAwayTeam();
    String playGame();
}

public class BaseBallGame implements Game  {

    private Team homeTeam;
    private Team awayTeam;
    private DataSource dataSource;
    
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public BaseBallGame(Team homeTeam, Team awayTeam) {
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
    }

    public BaseBallGame() {
    }

    @Override
    public Team getHomeTeam() {
        return homeTeam;
    }

    @Override
    public void setHomeTeam(Team homeTeam) {
        this.homeTeam = homeTeam;
    }

    @Override
    public Team getAwayTeam() {
        return awayTeam;
    }

    @Override
    public void setAwayTeam(Team awayTeam) {
        this.awayTeam = awayTeam;
    }

    @Override
    public String playGame(){
        return Math.random()<0.5? getHomeTeam().getName():getAwayTeam().getName();
    }
}

3.加载配置文件,获取bean

public class RunDemoInSpringWay {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
     
        Game game = context.getBean("game",Game.class);
        System.out.print(game.playGame());
        
        System.out.println(context.getBeanDefinitionCount());
        for (String string : context.getBeanDefinitionNames()) {
            System.out.println(string);
        }
    }
}

输出:


image.png

参考代码:

Github链接

2. Spring bean注解注入机制Demo:

2.1 @Configuration @Bean

  • @Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)
@Configuration
@ComponentScan(basePackages = "com.example.demo")
public class AppConfig {
    
    @Autowired
    private DataSource dataSource;
    
    @Resource
    private Team redSox;
    
    @Resource
    private Team cubs;
    
    @Bean
    public Game game(){
        BaseBallGame baseBallGame = new BaseBallGame(redSox, cubs);
        baseBallGame.setDs(dataSource);
        return baseBallGame;
    }

}
  • @Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象

bean类:

public interface Team {
    String getName();
}

@Component
public class Royals implements Team {
    @Override
    public String getName() {
        return "Kansas City Royals";
    }
}

@Component
public class RedSox implements Team {
    
    @Override
    public String getName() {
        return "Boston red sox";
    }
}

@Component
public class Cubs implements Team {

    @Override
    public String getName() {
        return "Chicago Cubs";
    }
}
public interface Game{
    void setHomeTeam(Team team);
    Team getHomeTeam();
    void setAwayTeam(Team team);
    Team getAwayTeam();
    String playGame();
}

@Component
public class BaseBallGame implements Game  {

    private Team homeTeam;
    private Team awayTeam;
    private DataSource ds;
    
    public void setDs(DataSource ds) {
        this.ds = ds;
    }

    public BaseBallGame(Team homeTeam, Team awayTeam) {
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
    }

    public BaseBallGame() {
    }

    @Override
    public Team getHomeTeam() {
        return homeTeam;
    }

    @Override
    public void setHomeTeam(Team homeTeam) {
        this.homeTeam = homeTeam;
    }

    @Override
    public Team getAwayTeam() {
        return awayTeam;
    }

    @Override
    public void setAwayTeam(Team awayTeam) {
        this.awayTeam = awayTeam;
    }

    @Override
    public String playGame(){
        return Math.random()<0.5? getHomeTeam().getName():getAwayTeam().getName();
    }
}

2.2 装配的两种方式

  • 1.@Autowired @Qualifier

@Autowired默认按类型装配(byType),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:

@Configuration
@ComponentScan(basePackages = "com.example.demo")
public class AppConfig {
    
    @Autowired
    private DataSource dataSource;
    
    @Autowired @Qualifier("redSox")
    private Team home;
    
    @Autowired @Qualifier("cubs")
    private Team away;
    
    @Bean
    public Game game(){
        BaseBallGame baseBallGame = new BaseBallGame(home, away);
        baseBallGame.setDs(dataSource);
        return baseBallGame;
    }

}
    1. @Resource
      @Resource 默认按照名称进行装配(byName),名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名,按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
@Configuration
@ComponentScan(basePackages = "com.example.demo")
public class AppConfig {
    
    @Autowired
    private DataSource dataSource;
    
    @Resource
    private Team redSox;
    
    @Resource
    private Team cubs;
    
    @Bean
    public Game game(){
        BaseBallGame baseBallGame = new BaseBallGame(redSox, cubs);
        baseBallGame.setDs(dataSource);
        return baseBallGame;
    }

}

2.3 主方法测试类:

利用AnnotationConfigApplicationContext加载配置类。

public class RunDemoInSpringWay {
    public static void main(String[] args){
        @SuppressWarnings("resource")
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Game game = context.getBean("game",Game.class);
        System.out.print(game.playGame());
        
        System.out.println(context.getBeanDefinitionCount());
        for (String string : context.getBeanDefinitionNames()) {
            System.out.println(string);
        }
    }
}

输出:

image.png

参考代码:

Github链接

相关文章

网友评论

      本文标题:Spring的注解注入机制与XML注入机制

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