在Spring开发中对于一些简单的bean,我们可以不使用XML文档直接注册bean。以达到简单方便的目的.
1.@Configuration
@Configuration:指示一个类声明一个或多个@Bean方法,可以由Spring容器处理。一般配合@Bean
在config包下建立类
public class UserConfig {
@Bean //注册bean
public User getUser(){
return new User();
}
@Bean//注册bean
public OtherUser getOtherUser(){
return new OtherUser();
}
}
使用@Bean之后,其bean就已经注册于ioc容器中,其相当于XML文档中的
<bean id="getUser" class="com.tang.pojo.User" />
<bean id="getOtherUser" class="com.tang.pojo.OtherUser" />
在pojo包下建立两个类:
public class User {
public String name;
public String getName() {
return name;
}
@Value("啦啦啦啦")
public void setName(String name) {
this.name = name;
}
}
public class OtherUser {
public String name;
public String getName() {
return name;
}
@Value("噜啦噜啦嘞")
public void setName(String name) {
this.name = name;
}
}
测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
User user = (User) context.getBean("getUser");
OtherUser otherUser = (OtherUser) context.getBean("getOtherUser");
System.out.println(user.getName());
System.out.println(otherUser.getName());
}
}
注:使用AnnotationConfigApplicationContext来注册其@Configuration注释的类和普通@Component类型
测试结果:
啦啦啦啦
噜啦噜啦嘞
2.@ComponentScan
@ComponentScan:来定义一个包扫描,在这些包中通过@Component在注册到 ico 容器中
在config包下建立类
@ComponentScan("com.tang.pojo")//写了这个包扫描就可以不用再去@bean或者显示的写User,因为其已经通过@Component注册到ico容器里
public class UserConfig {
}
在com.tang.pojo包下建立两个类:
@Component("user")
public class User {
public String name;
public String getName() {
return name;
}
@Value("啦啦啦啦")
public void setName(String name) {
this.name = name;
}
}
@Component("otheruser")
public class OtherUser {
public String name;
public String getName() {
return name;
}
@Value("噜啦噜啦嘞")
public void setName(String name) {
this.name = name;
}
}
测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
User user = (User) context.getBean("user");
OtherUser otherUser = (OtherUser) context.getBean("otheruser");
System.out.println(user.getName());
System.out.println(otherUser.getName());
}
}
注:这里getBean所拿到的名称一定与@Component(“名称”)相同,一般自定义
测试结果:
啦啦啦啦
噜啦噜啦嘞