5----------注解开发

前言

必须导入aop包

还得要引入一个context约束

实体类

package demo2.com.sicheng.entity;


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

import java.util.List;

@Component("江喆傻逼")
public class Hello {

    @Value("NMSL")
    private String name;

    @Autowired
    private List<Person> person;

    public String getName() {
        return name;
    }

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

    public List<Person> getPerson() {
        return person;
    }

    public void setPerson(List<Person> person) {
        this.person = person;
    }

    public Hello(String name, List<Person> person) {
        this.name = name;
        this.person = person;
    }

    public Hello() {
    }

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                ", person=" + person +
                '}';
    }
}
package demo2.com.sicheng.entity;

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

@Component("确实")
public class Person {

    @Value("123")
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(int age) {
        this.age = age;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}

spring配置文件

<?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
       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:annotation-config/>
    <context:component-scan base-package="demo2.com.sicheng.entity"/>
</beans>

测试文件

import demo2.com.sicheng.entity.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void HelloTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Hello hello = (Hello)context.getBean("江喆傻逼");
        System.out.println(hello.toString());
    }
}

重点注解:

 

 对于@Component注解:

  • @Controller:web层
  • @Service:service层
  • @Reposity:dao层

知识点总结

xml与注解比较

  • XML可以使用任何场景,结构清晰,维护方便
  • 注解不是自己提供得类使用不了,开发简单方便

xml与注解整合开发

  • xml管理bean:就是每一个类,都再xml中注册
  • 注解完成属性注入:属性注入,就用注解

 

posted @ 2020-06-18 10:54  梦想成为DALAO  阅读(203)  评论(0编辑  收藏  举报