1、xml形式
Person.java
package com.jackhu.bean;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "com.jackhu.bean.Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
}
}
beans.xml
MainTest.java
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
运行结果如下:
2、注解形式
/**
* 配置类==配置文件
*
* @Configuration 告诉Spring这是一个配置类
* @Bean 给容器中注册一个Bean,类型为返回值类型,id默认是方法名作为id
*/
@Configuration
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
public class MainTest {
public static void main(String[] args) {
// 1、xml形式
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// Person person = (Person) applicationContext.getBean("person");
// System.out.println(person);
// 2、注解形式
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name : namesForType) {
System.out.println(name);
}
}
}
3、包扫描@ComponentScan
@Configuration
@ComponentScan(value = "com.jackhu")
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
测试类
public class IOCTest {
@Test
public void main() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
// 容器中所有bean名称
String[] names = applicationContext.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
}
增加组件标记
输出结果:
源码解析:
@Configuration
@ComponentScan(value = "com.jackhu", excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class}) // excludeFilters排除 Controller和Service注解不加进来
})
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
includeFilters同理
文章来源: www.oschina.net,作者:叶湘伦,版权归原作者所有,如需转载,请联系作者。
原文链接:https://my.oschina.net/u/3915790/blog/3145644