@Configuration 表示此类是一个配置类,和用xml表示的配置文件相同
@Bean表示注册一个组件,注册的bean的类型为方法返回值的类型
package com.zyc.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import com.zyc.spring.bean.Person;
//配置类
@Configuration
public class MainConfig {
@Bean("person1")
public Person person(){
return new Person("li",9);
}
}
对应测试类
package com.zyc.spring.cases;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.zyc.spring.bean.Person;
import com.zyc.spring.config.MainConfig;
public class MainCase {
public static void main(String[] args) {
// ApplicationContext application = new ClassPathXmlApplicationContext("beans.xml");
// Object bean = application.getBean("person");
// System.out.println(bean);
ApplicationContext an = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = an.getBean(Person.class);
String[] names = an.getBeanNamesForType(Person.class);
for(String str :names){
System.out.println(str+"===");
}
}
}
pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zyc.spring</groupId>
<artifactId>springL</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springL</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
pojo
package com.zyc.spring.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;
}
public Person(String name,int age){
name = this.name;
age = this.age;
}
public Person(){
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}