六、注解使用方法-Spring快速入门小白编

步骤:
1.在类中加入@Component
2.在xml里增加扫描
<context:component-scan base-package="com.bb.dao"></context:component-scan>
命名空间为: xmlns:context="http://www.springframework.org/schema/context"

@Component可细化为:
@Repository dao层
@Service service层
@Controller controller层
@Autowired 自动装配

新建AddStudent.java实体类
AddStudent.java

package com.bb.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Component("addstudent")
public class AddStudent {
    private Integer addId;
    private String addName;

    public AddStudent() {
    }

    public AddStudent(Integer addId, String addName) {
        this.addId = addId;
        this.addName = addName;
    }

    public Integer getAddId() {
        return addId;
    }
    //使用set方法 对属性赋值@Value()
    @Value("1")
    public void setAddId(Integer addId) {
        this.addId = addId;
    }

    public String getAddName() {
        return addName;
    }
    //使用set方法 对属性赋值@Value()
    @Value("bb")
    public void setAddName(String addName) {
        this.addName = addName;
    }
}

applicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       default-autowire="byName"
       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">
<!--        配置扫描器-->
    <context:component-scan base-package="com.bb.dao"></context:component-scan>

TestSpring.java

    //使用注解
    public static void Annotation(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AddStudent addstudent =(AddStudent) context.getBean("addstudent");
        System.out.println(addstudent.getAddId()+"---"+addstudent.getAddName());
    }

输出结果:

1---bb

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。