Spring学习笔记(05-基本注解)

1.工程目录如下


2.在spring核心配置文件中配置扫包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
						   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

	 <!-- 扫描指定包下(包含其子包下)所有的类中的注解 -->
	 <context:component-scan base-package="com.xiao.pojo"></context:component-scan>

</beans>

3.创建实体类User,并使用注解@Component

package com.xiao.pojo;

import org.springframework.stereotype.Component;
/**
 * @Author 笑笑
 * @Date 20:37 2018/06/04
 */
//括号中的参数是设置容器中该类对象的名称,如果不设置,默认为该类的首字母小写的名称
@Component("user")
public class User {

    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

4.测试类

import com.xiao.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @Author 笑笑
 * @Date 20:42 2018/06/04
 */  
public class SpringTest_01 {

    @Test
    public void  test(){
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从容器中获取user对象
        User user= (User) ac.getBean("user");
        //输出user对象
        System.out.println(user);
    }

}

运行测试类,输出结果如下


同样功能的注解还有另外的三个,不过在开发中使用在不同的层,分别是

    1.@Controller  (用于web层)

    2.@Service       (用于service层)

    3.@Repository (用于dao层)

5.设置对象作用范围的注解

如果要设置对象的作用范围,使用@Scope

如:@Scope(scopeName = "prototype")    这是将对象设置为原型类型

6.依赖注入的注解

    1. @Value注解

       

    2.@Autowired注解(自动装配)

    3.@Qualifier注解(与@Autowired注解一起使用可以指定spring容器自动装配的具体的对象)

  

猜你喜欢

转载自blog.csdn.net/u012430402/article/details/80572645