1. 导包 4+2+1

aop

 使用注解配置spring

2. 导入约束文件

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context.xsd

3. 指定扫描的包

<!--指定扫描的位置,自动扫描该包以及该包所有的子包-->
     <context:component-scan base-package="cn.hd.annotation"></context:component-scan>

4. 为类声明注解

 使用注解配置spring


在类上书写代码

@Component("user")

//@Controller("user")//web层
//
@Service("user") //service 层
//
@Repository("user")//dao层

//为了解决所有的bean都是同一个注解,导致层次不清淅,提出了三个新的注解

public class User { 相当于在.xml bean name=user class=cn.hd.annotationUser
    private String name;
    private Integer age;
    private String address;
    private Car car;

}

没有强制要求,都可以用,提倡按照他的本意去注解

 

修改Scope属性

@Scope(scopeName = "prototype") singleton|prototype 单例(默认)和多例

 

属性注入:

(1) 值类型: 注解写在属性上面,同时也可以写在set方法上面

@Value("张三")
private String name;
@Value("20")
private Integer age;
@Value("河南")
private String address;

(2) 引用类型:

// @Autowired //自动装配 如果只有一个对象  自动装配
//    @Qualifier("car2") //自动装配时有多个对象要指定那个对象,与自动装配结合使用
//    @Resource(name = "car")  //直接指定配置那个对象

private Car car;

(3) 创建对象后就执行的方法

@PostConstruct
public void init(){
    System.out.println("创建对象后自动执行");
}
@PreDestroy
public void destroy(){
    System.out.println("对象销毁前执行");
}

  

 

 

 

 

Spring结合junit

1. 导包

test

使用注解配置spring

 

2. 书写测试代码

@RunWith(SpringJUnit4ClassRunner.class)//结合junit测试
@ContextConfiguration("classpath:cn/hd/annotation/applicationContext.xml") //读取配置文件

  由于原来使用的是application对象,读取配置和获得bean对象

  但是现在没有了 又想获得对象

@Resource(name="user")
private User user;

相关文章:

  • 2021-11-25
  • 2018-05-23
  • 2021-12-19
  • 2021-05-19
  • 2021-11-30
  • 2018-07-17
  • 2020-04-26
  • 2021-04-06
猜你喜欢
  • 2021-03-01
  • 2021-09-26
  • 2021-12-12
  • 2021-08-19
  • 2021-09-03
  • 2021-09-05
  • 2021-06-11
相关资源
相似解决方案