Spring-注解的使用

1.定义School类

package top.wyyblog.DI;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * @author wyyblog.top
 * 与@Component注解相同,但意义不同的注解还有三个
 * @Repository:注解在Dao实现类上
 * @Service:注解在Service实现类上
 * @Controller:注解在SpringMVC 的处理器上
 * 
 */
@Component("school") //表示当前类被Spring容器所管理
public class School {

	@Value("极速学院")
	private String name;
	
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "School [name=" + name + "]";
	}
}


2.定义Student类

package top.wyyblog.DI;

import javax.annotation.Resource;

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

@Scope("prototype") //多例的
@Component("student")
public class Student {
	
	@Value("张三")
	private String name;
	@Value("23")
	private int age;
	//域属性注入
	/*	1.
	 *@Autowired //byType方式的注解注入
 	 */	
	/*  2.
	 *@Autowired				//byName方式的注解注入
	 *@Qualifier("school") 	//要求@Autowired和@Qualifier联合使用
	 */	
	/*	3.
	 * @Resource(name="school") byName方式
	 * @Resource				byType方式
	 */
	@Resource(name="school")
	private School school;
	
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void setSchool(School school) {
		this.school = school;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
	}	
}


3.完善配置文件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: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:component-scan base-package="top.wyyblog.DI" />
</beans>


4.测试Demo

package top.wyyblog.DI;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("top/wyyblog/DI/applicationContext.xml");
		Student student = (Student) context.getBean("student");
		System.out.println(student);
	}
}

5.文件结构


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值