Skip to content

feat(#1381): Add a way to specify "inject-only" with @JacksonInject #5175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -817,11 +817,23 @@ protected void addInjectables(DeserializationContext ctxt,
for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) {
AnnotatedMember m = entry.getValue();
final JacksonInject.Value injectableValue = introspector.findInjectableValue(m);
final Boolean optional = injectableValue == null ? null : injectableValue.getOptional();
final Boolean optional;
final Boolean useInput;

builder.addInjectable(PropertyName.construct(m.getName()),
m.getType(),
beanDesc.getClassAnnotations(), m, entry.getKey(), optional);
if (injectableValue == null) {
optional = null;
useInput = null;
} else {
optional = injectableValue.getOptional();
useInput = injectableValue.getUseInput();
}

// 04-Jun-2025, tatu: [databind#1381]: default for "useInput" is false
if (!Boolean.TRUE.equals(useInput)) {
builder.addInjectable(PropertyName.construct(m.getName()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is part I don't fully understand: if injectable is only added if no input is to be used, how do things work with useInput = false, injectable value being present.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per this test, with no input but injected value present, the injected value is always returned regardless of useInput:

@Test
@DisplayName("input NO, injectable YES, useInput DEFAULT|TRUE|FALSE => injected")
void test2() throws Exception {
    assertEquals("injected", injectedMapper.readValue(empty, InputDefault.class).getField());
    assertEquals("injected", injectedMapper.readValue(empty, InputTrue.class).getField());
    assertEquals("injected", injectedMapper.readValue(empty, InputFalse.class).getField());
}

I read it like "we have no input but we have a value to inject, so we don't care about anything else: let's use the injected value". Is this the expected behavior? Or you meant something else?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic-wise, yes, you are correct (expected behavior I agree with).

But I meant code; meaning... what does addInjectable() do -- to me, it's the thing that injects non-input (injectable) value. So why is that contingent on "useInput"? And I think check here seems wrong in that sense: injectable value may be needed even input is used.
It is not only injected if useInput is false (or missing); can also be injected if useInput is true but input has no value for property.

Copy link
Contributor Author

@giulong giulong Jun 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a way to eagerly discard the injectable if we're going to use the input anyways. I think it's better in terms of performance since any further evaluation is useless, and there are many methods involved down that path.
But I also get this:

injectable value may be needed even input is used

Not now maybe, but in general I get that if a field is marked as injected, we should add it to the internal injectables for whatever future logic.

I can try to change this, which means passing useInput to the builder (last param in the snippet), as we made for optional:

builder.addInjectable(PropertyName.construct(m.getName()),
                            m.getType(),
                            beanDesc.getClassAnnotations(), m, entry.getKey(), optional, useInput);

Maybe we could also think of passing the whole injectableValue to the builder, instead of passing its properties one by one.

But I think this is not going to be easy. What do you think, is it worth it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, figured it was meant as optimization.
But the problem with " if we're going to use the input anyways" is that there might not be any input.
So it's not "use input if any matching, otherwise null" but rather "use input if present; if not, use injected value". Otherwise why even mark it with @JacksonInject at all, actually.

So we cannot know statically which one to use.

And yes, I think this is necessary to handle properly.

But I understand things are messy, tricky, complicated, esp. when passing things via Constructors (CreatorProperty properties) vs Field/MethodProperty ones.

m.getType(),
beanDesc.getClassAnnotations(), m, entry.getKey(), optional);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.fasterxml.jackson.databind.deser.inject;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.OptBoolean;

import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MissingInjectableValueExcepion;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.testutil.DatabindTestUtil;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

class JacksonInject1381Test extends DatabindTestUtil
{
static class InputDefault
{
@JacksonInject(value = "key")
private final String field;

@JsonCreator
public InputDefault(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

static class InputTrue
{
@JacksonInject(value = "key", useInput = OptBoolean.TRUE)
private final String field;

@JsonCreator
public InputTrue(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

static class InputFalse
{
@JacksonInject(value = "key", useInput = OptBoolean.FALSE)
private final String field;

@JsonCreator
public InputFalse(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

private final String empty = "{}";
private final String input = "{\"field\": \"input\"}";

private final ObjectMapper plainMapper = newJsonMapper();
private final ObjectMapper injectedMapper = jsonMapperBuilder()
.injectableValues(new InjectableValues.Std().addValue("key", "injected"))
.build();

@Test
@DisplayName("input NO, injectable NO, useInput DEFAULT|TRUE|FALSE => exception")
void test1() {
assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputDefault.class));

assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputTrue.class));

assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputFalse.class));
}

@Test
@DisplayName("input NO, injectable YES, useInput DEFAULT|TRUE|FALSE => injected")
void test2() throws Exception {
assertEquals("injected", injectedMapper.readValue(empty, InputDefault.class).getField());
assertEquals("injected", injectedMapper.readValue(empty, InputTrue.class).getField());
assertEquals("injected", injectedMapper.readValue(empty, InputFalse.class).getField());
}

@Test
@DisplayName("input YES, injectable NO, useInput DEFAULT|FALSE => exception")
void test3() {
assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(input, InputDefault.class));

assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(input, InputFalse.class));
}

@Test
@DisplayName("input YES, injectable NO, useInput TRUE => input")
void test4() throws Exception {
assertEquals("input", plainMapper.readValue(input, InputTrue.class).getField());
}

@Test
@DisplayName("input YES, injectable YES, useInput DEFAULT|FALSE => injected")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to useInput's javadocs:

Default is OptBoolean.DEFAULT, which translates to OptBoolean.TRUE: this is
for backwards compatibility (2.8 and earlier always allow binding input value).

This combination: input YES, injectable YES, useInput DEFAULT should actually behave as if we had useInput = TRUE, that is dropping the injected value and returning the input.

Nevertheless, since useInput never worked that way, this would mean introducing breaking changes. My suggestion is to keep things as per this test and change the javadoc accordingly:

Default is OptBoolean.DEFAULT, which translates to OptBoolean.FALSE

void test5() throws Exception {
assertEquals("injected", injectedMapper.readValue(input, InputDefault.class).getField());
assertEquals("injected", injectedMapper.readValue(input, InputFalse.class).getField());
}

@Test
@DisplayName("input YES, injectable YES, useInput TRUE => input")
void test6() throws Exception {
assertEquals("input", injectedMapper.readValue(input, InputTrue.class).getField());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package com.fasterxml.jackson.databind.deser.inject;

import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.OptBoolean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MissingInjectableValueExcepion;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.testutil.DatabindTestUtil;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

class JacksonInject1381WithOptionalTest extends DatabindTestUtil {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class shows how the behavior changes for all the combinations of the other test class when all injected fields are optional. Do you think we still need a required property in the annotation?

I feel like combining useInput and optional would cover all cases, also because optional should drive the same logic (but reversed) of required. Given this, adding a required property would make things unclear for the users, and the internal logic would be quite messy. Does this make sense?


private static class InputDefault {

@JacksonInject(value = "key", optional = OptBoolean.TRUE)
private final String field;

@JsonCreator
public InputDefault(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

private static class InputTrue {

@JacksonInject(value = "key", useInput = OptBoolean.TRUE, optional = OptBoolean.TRUE)
private final String field;

@JsonCreator
public InputTrue(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

private static class InputFalse {

@JacksonInject(value = "key", useInput = OptBoolean.FALSE, optional = OptBoolean.TRUE)
private final String field;

@JsonCreator
public InputFalse(@JsonProperty("field") final String field) {
this.field = field;
}

public String getField() {
return field;
}
}

private final String empty = "{}";
private final String input = "{\"field\": \"input\"}";

private final ObjectMapper plainMapper = JsonMapper.builder().build();
private final ObjectMapper injectedMapper = JsonMapper.builder()
.injectableValues(new InjectableValues.Std().addValue("key", "injected"))
.build();

@Test
@DisplayName("optional YES, input NO, injectable NO, useInput DEFAULT|TRUE|FALSE => exception")
void test1() {
assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputDefault.class));

assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputTrue.class));

assertThrows(MissingInjectableValueExcepion.class,
() -> plainMapper.readValue(empty, InputFalse.class));
}

@Test
@DisplayName("optional YES, input NO, injectable YES, useInput DEFAULT|TRUE|FALSE => injected")
void test2() throws JsonProcessingException {
assertEquals("injected", injectedMapper.readValue(empty, InputDefault.class).getField());
assertEquals("injected", injectedMapper.readValue(empty, InputTrue.class).getField());
assertEquals("injected", injectedMapper.readValue(empty, InputFalse.class).getField());
}

@Test
@DisplayName("optional YES, input YES, injectable NO, useInput DEFAULT|TRUE|FALSE => input")
void test3() throws JsonProcessingException {
assertEquals("input", plainMapper.readValue(input, InputDefault.class).getField());
assertEquals("input", plainMapper.readValue(input, InputFalse.class).getField());
assertEquals("input", plainMapper.readValue(input, InputTrue.class).getField());
}

@Test
@DisplayName("optional YES, input YES, injectable YES, useInput DEFAULT|FALSE => injected")
void test4() throws JsonProcessingException {
assertEquals("injected", injectedMapper.readValue(input, InputDefault.class).getField());
assertEquals("injected", injectedMapper.readValue(input, InputFalse.class).getField());
}

@Test
@DisplayName("optional YES, input YES, injectable YES, useInput TRUE => input")
void test5() throws JsonProcessingException {
assertEquals("input", injectedMapper.readValue(input, InputTrue.class).getField());
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.fasterxml.jackson.databind.tofix;
package com.fasterxml.jackson.databind.deser.inject;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved since this should not fail anymore


import java.util.Objects;

Expand All @@ -10,7 +10,6 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.testutil.DatabindTestUtil;
import com.fasterxml.jackson.databind.testutil.failure.JacksonTestFailureExpected;

import static org.junit.jupiter.api.Assertions.assertEquals;

Expand Down Expand Up @@ -41,7 +40,6 @@ public String getField2() {
}

// [databind#2678]
@JacksonTestFailureExpected
@Test
void readValueInjectables() throws Exception {
final InjectableValues injectableValues =
Expand All @@ -57,8 +55,6 @@ void readValueInjectables() throws Exception {
final Some actualValuePresent = mapper.readValue(
"{\"field1\": \"field1value\", \"field2\": \"field2value\"}", Some.class);
assertEquals("field1value", actualValuePresent.getField1());

// if I comment @JacksonInject that is next to the property the valid assert is the correct one:
assertEquals("field2value", actualValuePresent.getField2());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.fasterxml.jackson.annotation.OptBoolean;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import com.fasterxml.jackson.databind.exc.MissingInjectableValueExcepion;
import com.fasterxml.jackson.databind.testutil.DatabindTestUtil;

Expand Down