【JavaSpring學習筆記】註解方式實現注入

1、註解的一些功能:

// 描述自定義註解的註解, 叫元註解
@Target(ElementType.METHOD)//註解的作用域在哪
@Retention(RetentionPolicy.RUNTIME)//註解什麼時候用
@Deprecated //說明這個方法不讓用了,在用的時候會劃黑線

 

2、

@Service 業務層

@Conponent  公共組建 

@Controller 控制用戶跳轉 用在SpringMVC

 

3、實例

首先在XML文件寫一句全局掃描

 <context:component-scan base-package="com.hewenjie.**"/>

然後實例一個類

package com.hewenjie.service;

import org.springframework.stereotype.Service;

/**
 * @author 賀文傑
 * 2018/7/31 21:31
 */
@Service
public class UserServiceImpl implements UserService {
    public void say() {
        System.out.println("hello world");
    }
}

在類前面加上@Service ,這樣Spring就可以掃描到這個類了,在主函數中調用

public class Main {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");

        context.getBean(UserServiceImpl.class).say();
    }
}

成功輸出Helloworld;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章