spring注解spare

1、@Value

       从当前的配置文件中读取参数,格式为

    @Value("${TypeName}")
    private Type typeName;

      会自动进行类型转换。

2、@Component

      只有加了这个注解的类才可以被@Autowired使用。

目录

1、@Value

2、@Component

3、@ConfigurationProperties

4.使用注解来构造IoC容器


      从当前的配置文件中读取一整个集合类型。如,当前配置文件中有一个集合配置为

   dog:
     age: 10
     type: "哈士奇"
     favorite: "拆家"

      然后编写一个类如Dog,注意所有的属性都要添加get和set方法

@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
    private int age;
    private String type;
    private String favorite;

      为类配置@ConfigurationProperties注解,参数prefix为配置文件中集合的前缀,再为其加上@Component注解,就可以在其它类中引入它了,如下

@Autowired 
private Dog dog;

顺带介绍一下springboot中控制类的注解为@RestController,它相当于@Controller加@ResponseBody。

      控制类中的方法注解为@RequestMapping,格式如下,多个请求名用逗号隔开

@RequestMapping(value = {"/dog"} , method = RequestMethod.GET)

    还有简略写法@GetRequestMapping 和 @PostRequestMapping 相当于把后面的method省略掉了。

4.使用注解来构造IoC容器

用注解来向Spring容器注册Bean。需要在applicationContext.xml中注册<context:component-scan base-package=”pagkage1[,pagkage2,…,pagkageN]”/>

如:在base-package指明一个包

1 <context:component-scan base-package="cn.gacl.java"/>

表明cn.gacl.java包及其子包中,如果某个类的头上带有特定的注解【@Component/@Repository/@Service/@Controller】,就会将这个对象作为Bean注册进Spring容器。也可以在<context:component-scan base-package=” ”/>中指定多个包,如:

1 <context:component-scan base-package="cn.gacl.dao.impl,cn.gacl.service.impl,cn.gacl.action"/>

目录

1、@Value

2、@Component

4、@RestController 和 @RequestMapping


     引用:https://blog.csdn.net/qq_32881383/article/details/77982227

猜你喜欢

转载自blog.csdn.net/qq_37511875/article/details/81514441