Spring使用注解开发

导包

在这里插入图片描述

设置注解扫描范围

<context:component-scan base-package="com.tl"/>

使用注解完成依赖注入

注解注入不需要set方法

配置

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
        <!--设置注解扫描范围-->
        <context:component-scan base-package="com.tl"/>
        <!--开启注解-->
        <context:annotation-config/>

</beans>

实体类

People

package com.tl.pojo;

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

/**
 * @author tl
 */
@Component
public class People {
    @Value("tl")
    private String name;
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;

    public People() {
    }

    public String getName() {
        return name;
    }
    
    public Dog getDog() {
        return dog;
    }


    public Cat getCat() {
        return cat;
    }

}

Cat

package com.tl.pojo;

import org.springframework.stereotype.Component;

/**
 * @author tl
 */
@Component
public class Cat {
    public void shout(){
        System.out.println("喵~");
    }
}

Dog

package com.tl.pojo;

import org.springframework.stereotype.Component;

/**
 * @author tl
 */
@Component
public class Dog {
    public void shout(){
        System.out.println("汪~");
    }

}

测试类

从Spring容器中取对象时,根据对象类名来取。

import com.tl.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author tl
 */
public class Test {
    @org.junit.Test
    public void test1(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        People people = (People) context.getBean("people");
        people.getCat().shout();
        people.getDog().shout();
    }
}

使用注解注入属性

使用注解注入属性

Spring 的开发规范

1. 1. 1. xml用来管理bean;
2. 2. 2. 注解只负责完成属性的注入。

衍生注解

对应MVC三层架构
本质还是@Component。

dao 【@Repository】
service 【@Service】
controller 【@Controller
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值