package com.suirui.springanno;
import com.suirui.springanno.config.MainConfig;
import com.suirui.springanno.entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
public static void main(String[] args) {
/**
* 配置文件的方式
*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person pension = (Person) applicationContext.getBean("xmlBeanPerson");
System.out.println(pension);
// AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
// Person person = ac.getBean(Person.class);
// System.out.println(person);
}
}
2、注解方式注册组件
1 添加MainConfig.class 配置类,如下:
package com.suirui.springanno.config;
import com.suirui.springanno.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
@Bean("personAnno") //给容器注册一个bean,类型为返回值类型,id默认是方法名,可以通过注解value替换名称
public Person person() {
return new Person("zx",28);
}
}
2 创建test测试类,运行
package com.suirui.springanno;
import com.suirui.springanno.config.MainConfig;
import com.suirui.springanno.entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
public static void main(String[] args) {
// /**
// * 配置文件的方式
// */
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// Person pension = (Person) applicationContext.getBean("xmlBeanPerson");
// System.out.println(pension);
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = ac.getBean(Person.class);//获取所有的该类型的bean
System.out.println(person);
String[] beanNamesForType = ac.getBeanNamesForType(Person.class);//获取所有的该类型的bean名称
for (String s : beanNamesForType) {
System.out.println(s);
}
}
}