Spring基于注解方式实现对象创建(超详细)

89 阅读2分钟

基于注解方式实现对象创建

什么是注解

(1)注解是代码特殊标记,格式: @注解名称(属性名称=属性值,属性名称=属性…)
(2)使用注解,注解作用在类上面,方法上面,属性上面。
(3)使用注解目的:简化xml配置。

针对Bean管理中创建对象提供的注解

注解说明
@Component使用在类上用于实例化Bean
@Controller使用在web层类上用于实例化bean
@Service使用在service用于实例化bean
@Repository使用在dao层类上用于实例化bean

注意:这四个注解的功能是一样的都可以用来创建bean实例,用哪个都可以,只是为了区分,我们使用相对应的。

基于注解方式创建对象

引入依赖

spring-aop-5.2.6.RELEASE.jar引入到项目中。

拷贝到lib目录下

在这里插入图片描述

引入到项目中

在这里插入图片描述

开启组件扫描

引用context名称空间,配置需要扫描的包。

bean1.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">

    <!--开启组件扫描
    1、如果要扫描多个包,多个包用逗号隔开
    2、直接写到上层目录
    -->
    <context:component-scan base-package="com.Keafmd"></context:component-scan>

</beans>

创建个类开始使用

UserService类:

package com.Keafmd.spring5.service;

import org.springframework.stereotype.Service;

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-17 13:15
 */
//在注解里的value值可以不写,默认就是类的首字母小写 userService
// @Component(value = "userService")  //<bean id="userService" class=".."/>
@Service
public class UserService {

    public void add(){
        System.out.println("service add......");
    }
}

测试类:

package com.Keafmd.spring5.testdemo;

import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Keafmd
 *
 * @ClassName: TestSpring5Demo1
 * @Description: 测试类
 * @author: 牛哄哄的柯南
 * @date: 2021-01-17 13:03
 */
public class TestSpring5Demo1 {
    @Test
    public void testService(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService",UserService.class);
        System.out.println(userService);
        userService.add();
    }
}

测试结果:

com.Keafmd.spring5.service.UserService@436a4e4b
service add......

Process finished with exit code 0

以上就完成了基于注解的方式实现对象创建

看完如果对你有帮助,感谢点赞支持!
如果你是电脑端的话,看到右下角的 “一键三连” 了吗,没错点它[哈哈]

在这里插入图片描述

加油!

共同努力!

Keafmd