java 注解实例化_Spring之使用注解实例化Bean并注入属性

1.准备工作

(1)导入jar包

除了上篇文章使用到的基本jar包外,还得加入aop的jar包,所有jar包如下

format,png

所需jar包

(2)配置xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

2.注解实例化Bean

(1)实例化Bean有四个注解

@Component

@Service:业务层

@Controller:WEB层

@Repository:持久层

虽然分了层,但目前这四个注解的功能是一样的。

@Service(value = "user") //相当于bean标签中的id,四种方式功能一样

// @Component(value = "user")

// @Controller(value = "user")

// @Repository(value = "user")

@Scope(value = "singleton")

public class User {

public void print() {

System.out.println("user......");

}

}

@Test

/**

* 使用注解实例化User类

*/

public void testUser() {

// 读取配置文件

@SuppressWarnings("resource")

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

User user = (User)context.getBean("user");

user.print();

}

bean的作用域配置

Spring中可以使用scope属性来配置bean的作用域:

singleton:单例,在初始化配置文件时生成单例bean对象

prototype:原型的,在初始化配置文件时不生成bean对象,使用时返回不同的bean对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值