Spring 注解配置进阶

@Component

在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
        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="Demo"/>
    <context:annotation-config/>
</beans>

在类的定义时

package Demo.dao;

import org.springframework.stereotype.Component;

@Component
//等价于 <bean id="user" class="Demo.dao.User"/>
public class User {
    private String name;
}

此时该类就已经配置好了
可以通过@Value赋值

package Demo.dao;

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

@Component
//等价于 <bean id="user" class="Demo.dao.User"/>
public class User {
    @Value("jie")
    //赋值
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

还有很多其他方法 不细说

重点在于然后去均衡xml配置和注解配置

posted @ 2021-03-28 11:42  一个经常掉线的人  阅读(49)  评论(0)    收藏  举报