Spring(四)-注解

导入jar包
commons-logging.jar
spring.jar

配置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 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
        <!-- 开启注解配置  -->
        <context:annotation-config/>
        <!-- 当前扫描包 开启组件扫描  -->
        <context:component-scan base-package="com.fyl.entitiy"/>
</beans>

写实体类

package com.fyl.entitiy;

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

//Spring约束文件在这里
//C:\Users\lanou3g\Desktop\第三阶段\第7天_Spring\4.Resourse\spring-framework-4.1.4.RELEASE\docs\spring-framework-reference\html
@Component("person")
public class Person {
    
    //注入Student对象
    @Autowired//注意引入包为javax
    //@Resource(name="student")
    private Student stu;

    public Student getStu() {
        return stu;
    }
    
//  public void setStu(@Qualifier("stu") Student stu) {
    public void setStu(Student stu) {
        this.stu = stu;
    }
    
    public void say(){
        System.out.println("hello Person");
    }
}
package com.fyl.entitiy;

import org.springframework.stereotype.Component;

@Component("student")
public class Student {

    public void say(){
        System.out.println("hello Student");
    }
}

测试类

    @Test
    public void testConn(){
        //初始化Spring容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");//configLocation 配置路径
        //提取注解
        Person p=(Person)ctx.getBean("person");
        p.say();
        p.getStu().say();
        
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容