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

时间:2020-06-18 10:58:45   收藏:0   阅读:67

前言

必须导入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注解:

知识点总结

xml与注解比较

xml与注解整合开发

 

原文:https://www.cnblogs.com/sicheng-li/p/13156408.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!