spring框架注解笔记--@Import注解使用方式一

一、理解

    @Import注解是用来整合所有在@Configuration注解中定义的bean配置
    相当于spring利用xml方式配置bean,将多个(比如dao.xml、service.xml、controller.xml)配置bean的xml配置文件导入到单个xml文件的情形,此时容器启动时,就可以仅仅加载单个xml文件路径来实现dao、service、controller等bean实例的创建,@Import注解实现了相同的功能

二、代码实现

package com.springboot.demo.importAnnotation;

public interface Person {

    public void showPosition();
}

 

package com.springboot.demo.importAnnotation;

public class Teacher implements Person {

    @Override
    public void showPosition() {
        System.out.println("i am a teacher");
    }
}

 

package com.springboot.demo.importAnnotation;

public class Student implements Person {

    @Override
    public void showPosition() {
        System.out.println("i am a student");
    }
}

  相当于在spring的xml文件中配置bean实例

package com.springboot.demo.importAnnotation;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TeacherConfiguration {

    @Bean
    public Teacher getTeacher() {
        return new Teacher();
    }
}

  相当于在spring的xml文件中配置bean实例

package com.springboot.demo.importAnnotation;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StudentConfiguration {

    @Bean
    public Student getStudent() {
        return new Student();
    }
}

  相当于spring中import标签,整合多个配置文件

package com.springboot.demo.importAnnotation;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({TeacherConfiguration.class,StudentConfiguration.class})
public class MainConfiguration {
}

  

package com.springboot.demo.importAnnotation;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ImportAnnotationTest {

    public static void main (String args[]){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfiguration.class);
        Teacher t = context.getBean(Teacher.class);
        t.showPosition();
        Student s = context.getBean(Student.class);
        s.showPosition();
    }
}

  运行结果:

  i am a teacher

  i am a student

你可能感兴趣的:(spring)