spring的学习日记-spring-IOC-基于注解的方式开发-半注解

基于半注解的方式开发:

我们在使用注解开发的时候需要注意:

1.在xml中配置相关的资源,

2.在xml中开启支持注解开发

3.在xml中配置,使具体包下面的类的注解生效

 

4.在pojo层的注解为:@Component

   在dao层的注解为:@Repository

    在service层下面的注解为:@Service

   在control层下面的注解为:@Controller

以上的注解就相当于在xml中注册相应的bean,也就是new一个对象

 

pojo层:

package com.fu.pojo;

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

@Component
public class User {

    @Value("1")
    private int id;
    @Value("张三")
    private String name;
    @Value("123456")
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
        System.out.println("有参构造创建对象");
    }

    public User() {
        System.out.println("无参构造创建对象");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

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

 

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:annotation-config/>

<!--    使对应包下面的类生效-->
    <context:component-scan base-package="com.fu.pojo"/>

</beans>

 

测试类:

import com.fu.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        //获取IOC容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //有了容器我们就get到what
        User user = context.getBean("user", User.class);
        System.out.println(user);

    }
}

 

测试结果:

 

posted @ 2022-03-04 19:41  Fu_Zhang  阅读(34)  评论(0)    收藏  举报