1. 创建项目项目目录如下
── top
└── shuaiguo
├── config
│ ├── MyJavaConfig.java
│ └── MyJavaConfig2.java
└── pojo
├── User.java
└── User2.java
2. 添加相关注解
@Configuration
@Import(MyJavaConfig2.class)
public class MyJavaConfig {
@Bean
public User getUser(){
return new User();
}
}
增加@Configuration 标识这是个配置类
增加@Import(MyJavaConfig2.class) 引入其他配置类的内容
增加@Bean ,标识这是个bean,用于把bean添加到容器
3. 编写测试类
public class MyTest {
@Test
public void testCase001(){
ApplicationContext context = new AnnotationConfigApplicationContext(MyJavaConfig.class);
User user = context.getBean("getUser",User.class);
User2 user2 = context.getBean("getUser2",User2.class);
System.out.println(user.getName());
System.out.println(user2.getName());
}
}
网友评论