学习记录之---- Spring注解实现IOC和DI

本文详细介绍了Spring框架中注解的使用,包括@Component、@Autowired、@Repository、@Service和@Controller等,以及如何通过注解进行依赖注入和配置连接池,以实现三层架构的简单构建。
摘要由CSDN通过智能技术生成

        今天学习了spring的注解操作,当然还没有深入,都是一些基础操作,记录总结一下 😀

Spring注解实现IOC

注解:

@Component ---组件 在bean类需要被控制的类上面加上  

格式:

 1.@Componet("xx")   ---value只有一个时可以省略
 2.@Componet   ----默认是当前类名的小写类名   比如:User类默认为user
 3.@Componet(value="xx")   

1.配置文件开启注解扫描---需要更新头声明 (如果使用5.0以上得context.jar包需要导入aop.jar包)  扫描包下的注解


    <!--    开启注解扫描-->
 <context:component-scan base-package="com.gec"></context:component-scan>

2.测试 加载配置文件,然后通过Spring容器获取对象 可以打印配置文件的beanNames看看

注意点:

1.扫描包路径是否包含对象 ---建议使用父包扫描,范围更大更方便

2.注解的value只有一个时可以直接写值,省略value= (很多注解都可以,像@Webservlet注解name只有一个时也可以简写为”xx“)

IOC中的其他注解:

@Service

@Resipository(作用dao层)

@Controller

@Component-作用在类上,单纯创建bean对象

其他和@Component注解作用一致,

命名不同只是为了三层架构的注解区分-----更直观也更易读

😄小结: 

IOC方式有如下:

1.使用配置的bean标签---需要自己配置对应的对象

2.使用注解--比较方便吧,而且注解也更好的区分了三层架构的IOC,在配置中使用扫描注解标签即可

Spring注解如何注入依赖?

也是需要注解来注入依赖的---需要先导入aop.jar包

(突击考察----还记得DI三个注入方式吗?)

4个注解
  • @Value 注入int、float、String等基本数据类型,只能标注在成员变量、setter方法上。

  • @Autowired 按类型自动装配,可标注在成员变量(官方不推荐)、构造方法、setter方法上。

  • @Qualifier 按名称自动装配,需要和@Autowired搭配使用,只能标注在成员变量(官方不推荐)、setter方法上。

  • @Resource 按名称或类型自动装配,需要第三方包 javax.annotation.jar 的支持,只能标注在成员变量、setter方法上。

以上3个注解用于自动装配其它bean的实例,尽量标注在setter方法上。

复杂类型需要用xml方式注入

注解DI给基本类型注入值

1.bean类---给成员注入值

package com.gec.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component(value = "user")
public class User {

    @Value("01")
    private Integer id;
    @Value("小嘎嘎嘎")
    private String username;
    @Value("广州从化")
    private String address;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

测试

public static void main(String[] args) {

      //  1.加载applicationContext.xml  ---获取容器对象
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.获取对象

        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }
    
 

打印结果 java User{id=1, username='小嘎嘎嘎', address='广州从化'}

成功注入 -----而且注解方式不需要提供set方法

注解注入对象@Autowired

@Autowired---自动装配 按照类型

1.首先到目标类 ---girl类注入值到成员---也是通过value

@Component(value = "girl")
public class Girl {

    @Value(value = "001")
    private Integer girlid;
    @Value(value = "王冰冰")
    private String girlname;
    @Value(value = "女")
    private String girlgender;
    @Value(value = "山东")
    private String address;

2.user类加上girl类

  @Autowired
    private Girl mygirl;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", mygirl=" + mygirl +
                '}';
    }

测试输出:

User{id=1, username='小嘎嘎嘎', address='广州从化', mygirl=Girl{girlid=1, girlname='王冰冰', girlgender='女', address='山东'}}

当我user类有多个相同对象怎么办?

可以结合使用之前方法---xml配置注入

   <bean name="girl2" class="com.gec.pojo.Girl"  >
        <property name="girlid" value="002"></property>
        <property name="girlname" value="未知"></property>
        <property name="girlgender" value="女"></property>
        <property name="address" value="未知"></property>
    </bean>

注意:

@Autowired---根据类型自动装配

成员对象的名称和Componet的value有关联

(成员对象名称如果和对象注解value一致则默认装配注解注入的值,否则没有指定会报错)

可以引入@Qualifier注解--指定名称

@Autowired
@Qualifier("girl")
private Girl mygirl;

或者使用jdk提供的注解 @Resource

@scope注解,可以注解对象的作用域---单例/多例
@Scope(scopeName = "prototype")
或者
@Scope(value = "prototype")
  

两种写法效果都一样,看源码

public @interface Scope {
    @AliasFor("scopeName")
    String value() default "";

    @AliasFor("value")
    String scopeName() default "";

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;

可以发现有@AliasFor(),这个东西,这个其实就是起别名,所以这两个相当于互相起别名,

为啥呢要互相起别名呢?我也不知道。。。

注:alias是别名 数据库中的as是缩写,mybaties中也有

注解+xml+连接池构建三层架构操作

思路:分析架构之间需要的操作

 

步骤

1.导入连接池jar包和数据库jar包

2.配置xml文件


    <!--    spring 管理druid连接池对象  -->
    <bean name="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_demo"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- spring  管理 dao对象-->
    <bean name="userDao" class="com.gec.dao.UserDaoImpl">
        <property name="druidDataSource" ref="druidDataSource"></property>
    </bean>

    <!--    spring 管理 service  IOC操作-->
    <bean name="userService" class="com.gec.service.UserServiceImpl">
        <!--       将dao 注入给 servic 中的 userdao 属性-->
        <property name="userDao" ref="userDao"></property>
    </bean>

    <!--    spring 管理 web IOC 操作-->
    <bean name="userWeb" class="com.gec.web.UserWeb">
        <!--       将servide 注入给 web 中的 userservice 属性-->
        <property name="userService" ref="userService"></property>
    </bean>

3.dao层实现类

public class UserDaoImpl implements UserDao {

    private DruidDataSource druidDataSource;

    public void setDruidDataSource(DruidDataSource druidDataSource) {
        this.druidDataSource = druidDataSource;
    }

    @Override
    public void addUser() throws SQLException {
        System.out.println("添加用户...");

        Connection connection = druidDataSource.getConnection();
        Statement statement = connection.createStatement();
        String sql="delete from tb_user where name='小黄' ;";
        statement.executeUpdate(sql);
    }
}

4.给ServiceImpl类创建UserDao对象,提供set方法 -----因为是通过xml的set注入

public class UserServiceImpl implements UserService {


    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addUser() throws SQLException {
        userDao.addUser();
    }
}

5.给Web层创建UserService对象,同上

public class UserWeb {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void addByUser() throws SQLException {
        System.out.println("----------------userweb 中方法 执行了---");
        userService.addUser();

    }

6.控制台输出如下-----()

 八月 15, 2023 7:11:53 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
 信息: {dataSource-1} inited

 druidDataSource
 userDao
 userService
 userWeb
 4
 ----------------userweb 中方法 执行了---
 添加用户...</span></span>

-----------ok-----------

其实我感觉最重要的还是spring的思想,通过IOC和DI注入来实现对象的生成与赋值

当然还有三层架构思想

总结 

1.IOC和DI综合案例---简单构建三层架构流程

使用注解先导入需要的依赖包并在配置开启扫描包开启注解

2.spring创建对象注解主要四个 ---IOC

  • @Component---单纯对象

  • @Repostory--dao

  • @Service--业务逻辑层

  • @Controller---视图层 web层

3.spring对象属性赋值注解---DI操作

  • @Value ---基本类型

  • @Autowired----自动装配 注意:需要成员名称与注解名称一致,大小写也一致 否则会报错

  • @Qualifier----限定器 ----指定@Autowired装配的对象的注解名称,需要搭配@Autowired使用

4.注解混合set方式----搭配XML+搭配连接池

主要注意的点是: 三层架构的层层依赖, xml配置-属性依赖 , dao层对连接池的操作

我觉得其实都还比较基础,虽然一开始我是一下子写不出来,但只要多操作就理解了,最重要还是操作的思路 🐒

----end----

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值