(2)Spring的bean管理(基于注解)

注解介绍
  1. 代码里的特殊标记,使用注解可以完成功能
  2. 写法:@注解名称(属性名称=value)
  3. 注解使用在 类上面,方法上面,属性上
  4. 作用:替代配置文件完成对象生成,属性注入,但是注解并不能完全脱离配置文件
Spring注解开发准备
  1. applicationContext.xml中引入新的约束



  1. 约束中开启注解扫描




    

注解创建对象

import org.springframework.stereotype.Component;

@Component(value="person")   //等于
public class Person{
    public void say(){
        System.out.println("hi");
    }
}
public class test {
    public static void main(String args []){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = (Person) context.getBean("person");
        person.say();
    }
}

创建对象一共有4个注解

  • @Component
  • @Controller:WEB层
  • @Service : 业务层
  • @Repository:持久层
    目前这四个注解功能一样

创建单实例对象:

@Component(value="person")   //等于
@Scope(value = "singleton")  //prototype创建多实例
public class Person{
    public void say(){
        System.out.println("hi");
    }
}
public class test {
    public static void main(String args []){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person1 = (Person) context.getBean("person");
        Person person2 = (Person) context.getBean("person");
        System.out.println(person1==person2);
    }
}

结果:
image.png

注解注入属性

  1. 注解注入对象
    场景:Service中注入Dao对象
@Component("studentDao")
public class studentDao {
    public void say(){
        System.out.println("this is dao");
    }
}
@Service("studentService")
public class StudentService {
    //在SerVice中注入Dao对象

    //创建Dao类型的属性,在属性上使用@Autowired实现对象注入(自动装配)
    @Autowired
    private studentDao studentDao;
    public void say2(){
        System.out.println("this is Service");
        studentDao.say();
    }
}

其实更常用对象注入的注解是:@Resource(name=" ")


@Service("studentService")
public class StudentService {
    //在SerVice中注入Dao对象
    //创建Dao类型的属性,在属性上使用@Resource实现对象注入
    @Resource(name = "studentDao")
    private studentDao studentDao;
    public void say2(){
        System.out.println("this is Service");
        studentDao.say();
    }
}

测试:

public class test {
    public static void main(String args []){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentService studentService = (StudentService) context.getBean("studentService");
        studentService.say2();
    }
}

结果:
image.png

你可能感兴趣的:((2)Spring的bean管理(基于注解))