Spring5 常用注解

1、注解配置

1.1、 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:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/context
                          https://www.springframework.org/schema/context/spring-context.xsd">

   <!--   扫描包     -->
   <context:component-scan base-package="com.chris"/>
   <!--   开启注解配置 -->
   <context:annotation-config/>


</beans>

 

1.2 、@Component

注入bean,XML中可以不用再继续配置bean

package com.chris.pojo;

import org.springframework.stereotype.Component;

@Component
public class UserPOJO {
   public String Name = "UserPOJO";
}

 

1.3 、衍生注解
1.31、@Repository(Dao层)、 @Service(Service层)、 @Controller(层)
package com.chris.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
   public String Name = "UserDao";
}
package com.chris.Services;

import org.springframework.stereotype.Service;

@Service
public class UserServices {
   public String Name = "UserServices";
}
package com.chris.Controller;

import org.springframework.stereotype.Controller;

@Controller
public class UserController {
   public String Name = "UserController";
}

 

1.32、注解注入
@Repository
public class UserSetDao {
   @Value("UserSetDao")
   private String Name;

   public String getName() {
       return Name;
  }
}

 

1.33、调用方式

 

import com.chris.dao.UserDao;
import com.chris.pojo.UserPOJO;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
   public static void main(String[] args) {
       ApplicationContext context = new ClassPathXmlApplicationContext("applictionContext.xml");
       UserPOJO userPOJO = (UserPOJO) context.getBean("userPOJO");
       System.out.println(userPOJO.Name);

  }
}
posted @ 2020-08-05 16:33  Chris丶Woo  阅读(314)  评论(0编辑  收藏  举报