Skip to content

Latest commit

 

History

History
124 lines (80 loc) · 4.23 KB

annotations.md

File metadata and controls

124 lines (80 loc) · 4.23 KB

Annotations

Spring

Core Spring Framework Annotations

@Transactional

@Resource vs. @Autowired (@Inject)

@Component vs. @Bean

@Component vs. @Service

@Component 跟 @Service @Controller @Repository 有什么区别?

@Bean 和 @Component 是不是同一种东西?是不同的概念!

Same is true for @Service and @Repository annotation, they are a specialization of @Component in service and persistence layer. A Spring bean in the service layer should be annotated using @Service instead of @Component annotation and a spring bean in the persistence layer should be annotated with @Repository annotation.

By using a specialized annotation we hit two birds with one stone. First, they are treated as Spring bean and second you can put special behavior required by that layer.

@Profile

References

Example : @ActiveProfile in Tests

  • SomeMessageReceiver.java
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Profile("mq")
@Component
public class SomeMessageReceiver {
    // ……
}
  • MqTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import xyz.icehe.java.demo.main.Application;

@ActiveProfiles("maxq")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class MqTest {

    @Autowired
    private SomeMessageReceiver someMessageReceiver;

    @Test
    public void sendMsg() {
        // ……
    }
}

Lombok

@Data

总结:lombok 的 @Data 注释导致的问题 (详见微博)

@Value

FastJson

@JSONField

Jackson

@JsonSerialize and @JsonDeserialize

@JsonInclude(Include.NON_NULL)