Spring配置记录

时间:2020-11-14 11:04:24   收藏:0   阅读:34

 

 

@Repository
@Service

@Component

在Spring中@Component,需要配置注解能使用,并且需要在配置文件中扫描到当前包,才能使用

使用ClassPathXmlApplicationContext 这个是针对于配置文件的

new ClassPathXmlApplicationContext("applicationContext.xml")
//如果失败就下面这样写(哪个都行)
new ClassPathXmlApplicationContext("file:E:\Code\2020\inJDstudy\spring-test\02-Spring\src\main\resources")
ApplicationContext context=new FileSystemXmlApplicationContext("src/main/resources/beans.xml");
?
ApplicationContext context=new FileSystemXmlApplicationContext("src/main/resources/beans.xml");

@Configuration

这是目前是spring推荐使用的方式

@Configuration代表这是一个配置类,把它看成applicationContext.xml就好了!!!

此时就是基于注解的

ApplicationContext context = new AnnotationConfigApplicationContext("com.jd.nxj.config");
Person person = context.getBean("person", Person.class);
       System.out.println(person.getName());

config:

@Configuration
public class TestConfig {
   //@Bean对应于<bean>标签
   //方法名person对应于bean的id
   //返回值对应bean的class
   @Bean
   public Person person(){
       //若person标注@Value了,这里即使赋值也是无效的!
       return new Person("aaa");
  }
}

component

@Component
public class Person {
   @Value("qwe")
   private String name;
?
   public Person() {
  }
   public Person(String name) {
       this.name=name;
  }
?
   public String getName() {
       return name;
  }
?
   public void setName(String name) {
       this.name = name;
  }
}

把它看成applicationContext.xml是没问题的,比如在config上加@ComponentScan("com.jd.nxj.pojo"),那么即使我不在config中配置person的bean,在person直接@Component也是可以直接生效的

 @Import 对应底层import标签,组合进来一起使用

 

原文:https://www.cnblogs.com/ningxinjie/p/13972273.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!