步骤:
1.在类中加入@Component
2.在xml里增加扫描
<context:component-scan base-package="com.bb.dao"></context:component-scan>
命名空间为: xmlns:context="http://www.springframework.org/schema/context"
@Component可细化为:
@Repository dao层
@Service service层
@Controller controller层
@Autowired 自动装配
新建AddStudent.java实体类
AddStudent.java
package com.bb.dao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Component("addstudent")
public class AddStudent {
private Integer addId;
private String addName;
public AddStudent() {
}
public AddStudent(Integer addId, String addName) {
this.addId = addId;
this.addName = addName;
}
public Integer getAddId() {
return addId;
}
//使用set方法 对属性赋值@Value()
@Value("1")
public void setAddId(Integer addId) {
this.addId = addId;
}
public String getAddName() {
return addName;
}
//使用set方法 对属性赋值@Value()
@Value("bb")
public void setAddName(String addName) {
this.addName = addName;
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
default-autowire="byName"
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:component-scan base-package="com.bb.dao"></context:component-scan>
TestSpring.java
//使用注解
public static void Annotation(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AddStudent addstudent =(AddStudent) context.getBean("addstudent");
System.out.println(addstudent.getAddId()+"---"+addstudent.getAddName());
}
输出结果:
1---bb