新建一个maven项目,导入jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
传统的开发方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.my.bean.Person">
<property name="name" value="张三"></property>
<property name="age" value="5"></property>
</bean>
</beans>
public class MainTest {
public static void main(String[] args) {
//xml方式获取Person的值
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//通过id获取
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
注解的方式
- @Configurable//告诉spring这是个配置类
- @Bean//给容器注册一个bean 类型为返回值类型 id默认是用方法名作为id
- @Bean(“person01”) id为person01
//配置类==配置文件
@Configurable//告诉spring这是个配置类
public class MainConfig {
/**
* @Bean("person01") id为person01
* @return
*/
@Bean//给容器注册一个bean 类型为返回值类型 id默认是用方法名作为id
public Person peron() {
return new Person("李四",20);
}
}
public static void main(String[] args) {
//注解方式获取Person的值
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
//通过类型获取
Person bean = annotationConfigApplicationContext.getBean(Person.class);
System.out.println(bean);
//获取所有自定义bean的名字
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
System.out.println(Arrays.toString(beanDefinitionNames));
//获取所有Person类型自定义bean的名字
String[] beanNamesForType = annotationConfigApplicationContext.getBeanNamesForType(Person.class);
System.out.println(Arrays.toString(beanNamesForType));
}