Spring 使用注解创建对象

今天药忘吃喽~ 2022-12-17 11:55 230阅读 0赞

引入AOP依赖(spring-aop-5.2.6.RELEASE.jar)

20201023161245702.png


一、创建类

在类上面添加创建对象的注解 @Component(value = “user”)

User.java

  1. /*
  2. 注解里面value属性值可以不写
  3. 默认是类名称,首字母小写
  4. */
  5. @Component(value = "user") //等于<bean id="userService" class="**.L_注解开发.a_对象创建">
  6. public class User {
  7. public void add(){
  8. System.out.println("add方法......");
  9. }
  10. }

#

二、编写配置文件

开启组件扫描:

bean21.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  7. <!--开启组件扫描
  8. 1.若要扫描多个包,多个包用逗号隔开
  9. 2.若要扫描多个包,扫描包的上级目录
  10. -->
  11. <context:component-scan base-package="com.health.IOC.L_注解开发.a_对象创建"></context:component-scan>
  12. </beans>

#

三、测试

TestLa.java

  1. public class TestLa {
  2. public static void main(String[] args) {
  3. ApplicationContext context =
  4. new ClassPathXmlApplicationContext("com/health/IOC/L_注解开发/a_对象创建/bean21.xml");
  5. User user = context.getBean("user", User.class);
  6. System.out.println(user);
  7. user.add();
  8. }
  9. }

输出结果:

20201023160317164.png

发表评论

表情:
评论列表 (有 0 条评论,230人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring使用注解方式注入对象

    上次Spring入门的时候我们使用的是最原始的方法来注入对象,这次我们用个有意思的方式——注解方式来注入对象,使用注解方式可以使得配置文件变得更加简洁,前面的准备工作可以看我的