第一步在xml文件中添加扫描,包的内容是注解包含的范围
<!--注解的扫描-->
<comtext:component-scan base-package="com.offcn.bean"/>
第二步在需要使用的类的上面加上注解@Component
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=context.getBean("user",User.class);
System.out.println(user);
可以直接获得相关的bean,bean的默认值为类的首字母小写
可以在类中赋值和起别名@Component(“abc”)
@AllArgsConstructor
@NoArgsConstructor
@Getter@Setter@ToString
@Component("abc")
public class User {
@Value("1")
private Integer id;
@Value("zhangs")
private String username;
@Value("mima")
private String password;
@Value("11")
private Integer age;
}
使用@Conponent限制:对于没有源代码的类只能使用xml格式
Spring注解配置与Bean实例化
本文介绍如何在Spring框架中使用注解进行配置,包括@Component注解的使用、属性注入以及通过@Component限定符指定Bean的名称。同时,演示了如何在XML配置文件中扫描注解,并通过ApplicationContext获取实例。
1488

被折叠的 条评论
为什么被折叠?



