1. 程式人生 > 實用技巧 >Spring配置記錄

Spring配置記錄

@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標籤,組合進來一起使用